Json.dumps (): removing slashes

Since slashes can only occur in strings inside a serialized JSON object and are not escaped (in the default settings), using

json.dump(some_dict).replace('/', r'\/') 

It works reliably, but it looks hacks.

I know that forward slashes should not be escaped, but you can avoid them, and for my utility I would like them to be escaped.

Is there a way to allow JSONEncoder to escape with a slash without manual escaping?

+4
json python serialization escaping
source share
1 answer

Only remove slashes when encode_html_chars = True

Check it out - https://github.com/esnme/ultrajson/pull/114

The JSON specification says that front slices should be hidden implicitly.

Here is the solution to do this in JSONEncoder itself. It’s just that you create an ESCAPE SCENARIO and do the calculations in front of you and later do the encoding.

https://chromium.googlesource.com/external/googleappengine/python/+/dc33addea2da464ca07e869cb11832e1ae82da9d/lib/django/django/utils/simplejson/encoder.py

Hope this helps.

-

Adding to the above solution, there is another reason to avoid characters. As kay said, this gives us extra sleep. It prevents an attack. Thus, the solution above takes care of all the problems.

 ESCAPE_DCT = { # escape all forward slashes to prevent </script> attack '/': '\\/', '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } 
+5
source share

All Articles