json.dumps(): escaping forward slashes

前端 未结 2 882
眼角桃花
眼角桃花 2021-01-02 15:56

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

json.dump(some_dict).re         


        
2条回答
  •  囚心锁ツ
    2021-01-02 16:00

    Only escape forward slashes when encode_html_chars=True

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

    The JSON spec says forward slashes shall be escaped implicitly.

    Here is a solution to do it in JSONEncoder itself. Its just that you create an ESCAPE DICTIONARY and do computation before hand and do the encoding later.

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

    Hope it helps.

    -

    Adding to the above solution, there is another reason to escape the characters. As kay said, it gives us some extra sleep. It prevents the attack. So the solution above takes care of all issues.

    ESCAPE_DCT = {
        # escape all forward slashes to prevent  attack
        '/': '\\/',
        '\\': '\\\\',
        '"': '\\"',
        '\b': '\\b',
        '\f': '\\f',
        '\n': '\\n',
        '\r': '\\r',
        '\t': '\\t',
    }
    

提交回复
热议问题