Skip to content

Commit

Permalink
fix(json): Escape most used special characters (such as \n, \t)
Browse files Browse the repository at this point in the history
Fix #18
  • Loading branch information
LukeSavefrogs committed Feb 12, 2024
1 parent cb33127 commit 6a15bf8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/polyfills/json/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@

__all__ = ["dumps", "dump", "loads", "load"]

# From the builtin `json` module:
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}


class BaseJSONError(Exception):
""" Base exception for the JSON library. """
Expand All @@ -32,9 +43,10 @@ def escape_string(string):
Returns:
str: The escaped string.
"""
return string \
.replace("\\", "\\\\") \
.replace('"', '\\"')
for special_char in ESCAPE_DCT.keys():
string = string.replace(special_char, ESCAPE_DCT[special_char])

return string

def dumps(
obj,
Expand Down
5 changes: 5 additions & 0 deletions src/polyfills/json/tests/dumps/test_dumps.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ def test_escape(self):
r"""{"k\\ey": "va\\lue"}""",
"Backslashes should be escaped both in keys and values"
)
self.assertEqual(
json.dumps("test\ntest"),
'"test\\ntest"',
"Newlines should be escaped"
)

def test_complex(self):
if str(1==1) == 'True':
Expand Down

0 comments on commit 6a15bf8

Please sign in to comment.