From 4f264330fda4c996b0f5a6764db529a9a5e56929 Mon Sep 17 00:00:00 2001 From: Luca Salvarani Date: Mon, 12 Feb 2024 15:17:02 +0100 Subject: [PATCH] fix(json): Fix escape not working properly on Python versions lower or equal than 3.5 --- src/polyfills/json/__init__.py | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/polyfills/json/__init__.py b/src/polyfills/json/__init__.py index 6f4f23f..c6d863b 100644 --- a/src/polyfills/json/__init__.py +++ b/src/polyfills/json/__init__.py @@ -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): @@ -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