Skip to content

Commit

Permalink
fix(json): Fix escape not working properly on Python versions lower o…
Browse files Browse the repository at this point in the history
…r equal than 3.5
  • Loading branch information
LukeSavefrogs committed Feb 12, 2024
1 parent 5c3e89d commit 4f26433
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/polyfills/json/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,20 @@

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

# From the builtin `json` module:
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
# The following list of characters is taken from the builtin `json` module.
#
# I used a list instead of a dictionary because on Py<=3.5 dictionaries are
# unordered by default, which is a problem in this case since the backslash
# may be escaped multiple times.
ESCAPED_CHARS = [
{"from": '\\', "to": '\\\\'},
{"from": '"', "to": '\\"'},
{"from": '\b', "to": '\\b'},
{"from": '\f', "to": '\\f'},
{"from": '\n', "to": '\\n'},
{"from": '\r', "to": '\\r'},
{"from": '\t', "to": '\\t'},
]


class BaseJSONError(Exception):
Expand All @@ -43,8 +47,8 @@ def escape_string(string):
Returns:
str: The escaped string.
"""
for special_char in ESCAPE_DCT.keys():
string = string.replace(special_char, ESCAPE_DCT[special_char])
for special_char in ESCAPED_CHARS:
string = string.replace(special_char["from"], special_char["to"])

return string

Expand Down

0 comments on commit 4f26433

Please sign in to comment.