Skip to content

Commit

Permalink
Add 'Stringify JSON' keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
peritus committed Oct 14, 2012
1 parent 1309bad commit 6d1ef22
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/HttpLibrary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,14 +495,33 @@ def should_be_valid_json(self, json_string):

def parse_json(self, json_string):
"""
Parses the JSON document `json_string` and returns a Python datastructure.
Parses the JSON document `json_string` and returns a data structure.
Example:
| ${result}= | Parse Json | [1, 2, 3] |
| Length Should Be | ${result} | 3 |
`json_string` is the string containg JSON that will be parsed
"""
return load_json(json_string)

def stringify_json(self, data):
"""
Converts the data structure to a string containing its JSON string representation
Example:
| ${data} = | Create List | 1 2 3 |
| ${json_string}= | Stringify JSON | ${data} |
| Should Be Equal As Strings | ${json_string} | ["1", "2", "3"] |
`data` is the data structure to convert to json
"""

try:
return json.dumps(data)
except ValueError, e:
raise ValueError("Could not stringify '%r' to JSON: %s" % (data, e))

@_with_json
def get_json_value(self, json_string, json_pointer):
"""
Expand Down
13 changes: 13 additions & 0 deletions tests/json.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
*** Setting ***

Library HttpLibrary.HTTP
Library Collections

*** Test Cases ***

Expand Down Expand Up @@ -96,3 +97,15 @@ Json Value Should Be Fail Invalid Pointer
... JsonPointerException: 'baz' not found in {u'foo': {u'bar': [4, 5, 6]}}
... Json Value Should Equal ${doc} /baz [7,8,9]

Stringify Documentation Example
${data} = Create List 1 2 3
${json_string}= Stringify JSON ${data}
Should Be Equal As Strings ${json_string} ["1", "2", "3"]

Stringify Complex Object
${names} = Create List First Name Family Name Email
${data} = Create Dictionary names ${names} a 1 b 12
${json_string}= Stringify JSON ${data}

Should Be Equal As Strings ${json_string} {"a": "1", "b": "12", "names": ["First Name", "Family Name", "Email"]}

0 comments on commit 6d1ef22

Please sign in to comment.