Skip to content

Commit

Permalink
Fixed issue with escaping special characters in JSON string pretty pr…
Browse files Browse the repository at this point in the history
…inting

Signed-off-by: Ole Herman Schumacher Elgesem <ole@northern.tech>
  • Loading branch information
olehermanse committed Sep 21, 2021
1 parent 176173d commit d9865d1
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
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
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 d9865d1

Please sign in to comment.