Skip to content

Commit 6d1ef22

Browse files
committed
Add 'Stringify JSON' keyword
1 parent 1309bad commit 6d1ef22

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/HttpLibrary/__init__.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,14 +495,33 @@ def should_be_valid_json(self, json_string):
495495

496496
def parse_json(self, json_string):
497497
"""
498-
Parses the JSON document `json_string` and returns a Python datastructure.
498+
Parses the JSON document `json_string` and returns a data structure.
499499
500500
Example:
501501
| ${result}= | Parse Json | [1, 2, 3] |
502502
| Length Should Be | ${result} | 3 |
503+
504+
`json_string` is the string containg JSON that will be parsed
503505
"""
504506
return load_json(json_string)
505507

508+
def stringify_json(self, data):
509+
"""
510+
Converts the data structure to a string containing its JSON string representation
511+
512+
Example:
513+
| ${data} = | Create List | 1 2 3 |
514+
| ${json_string}= | Stringify JSON | ${data} |
515+
| Should Be Equal As Strings | ${json_string} | ["1", "2", "3"] |
516+
517+
`data` is the data structure to convert to json
518+
"""
519+
520+
try:
521+
return json.dumps(data)
522+
except ValueError, e:
523+
raise ValueError("Could not stringify '%r' to JSON: %s" % (data, e))
524+
506525
@_with_json
507526
def get_json_value(self, json_string, json_pointer):
508527
"""

tests/json.txt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
*** Setting ***
22

33
Library HttpLibrary.HTTP
4+
Library Collections
45

56
*** Test Cases ***
67

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

100+
Stringify Documentation Example
101+
${data} = Create List 1 2 3
102+
${json_string}= Stringify JSON ${data}
103+
Should Be Equal As Strings ${json_string} ["1", "2", "3"]
104+
105+
Stringify Complex Object
106+
${names} = Create List First Name Family Name Email
107+
${data} = Create Dictionary names ${names} a 1 b 12
108+
${json_string}= Stringify JSON ${data}
109+
110+
Should Be Equal As Strings ${json_string} {"a": "1", "b": "12", "names": ["First Name", "Family Name", "Email"]}
111+

0 commit comments

Comments
 (0)