Skip to content

Commit

Permalink
Merge pull request #19 from cfengine/pretty
Browse files Browse the repository at this point in the history
Fixed issue with escaping special characters in JSON string pretty printing
  • Loading branch information
olehermanse authored Sep 22, 2021
2 parents 176173d + d9865d1 commit c906820
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion cfbs/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ def _encode(data, indent, cursor):
elif isinstance(data, (int, float)):
return repr(data)
elif isinstance(data, str):
return '"' + data + '"'
# Use the json module to escape the string with backslashes:
return json.dumps(data)
elif isinstance(data, (list, tuple)):
return _encode_list(data, indent, cursor)
elif isinstance(data, dict):
Expand Down
18 changes: 18 additions & 0 deletions test/test_pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ def test_pretty():
expected = '{ "a": null, "b": true, "c": false, "d": 1, "e": 1.2, "f": "Hello!" }'
assert pretty(test) == expected

# Test that strings are escaped correctly:

test = "" # Empty string
expected = '""' # is represented as "" in JSON, same as python
assert pretty(test) == expected

test = r'""' # Putting double quotes inside the string
expected = r'"\"\""' # means they have to be escaped with backslashes
assert pretty(test) == expected

test = '\n' # A newline character
expected = r'"\n"' # is encoded as \n, same as python
assert pretty(test) == expected

test = r'\ ' # A backslash character
expected = r'"\\ "' # represented by two backslashes in JSON
assert pretty(test) == expected


def test_pretty_string():
# Test primitives
Expand Down

0 comments on commit c906820

Please sign in to comment.