json.dumps():转义正斜杠 [英] json.dumps(): escaping forward slashes

查看:4722
本文介绍了json.dumps():转义正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于正斜杠只能发生在JSON序列化对象中的字符串中,并且不会转义(在默认设置中),使用

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





我知道,正斜杠不必转义,但您可以可能逃避他们,对于我的用户名,我想让他们逃脱。



有没有办法让JSONEncoder在没有手动转义的情况下转义斜杠他们?

解决方案

只有在encode_html_chars = True 才能退出正斜杠

查看此 -
https://github.com/ esnme / ultrajson / pull / 114



JSON规范表示,正确的slahes应该隐式转义。



这是JS中的一个解决方案ONEncoder本身。它只是你创建一个ESCAPE DICTIONARY并在手之前进行计算,然后进行编码。





希望有帮助。



-



添加到上述解决方案中,还有另一个原因可以转义字符。正如 kay 所说,它给我们一些额外的睡眠。它可以防止攻击。所以上面的解决方案是处理所有问题。

  ESCAPE_DCT = {
#转义所有正斜杠以防止& /脚本>攻击
'/':'\\ /',
'\\':'\\\\'',
'' \,
'\b':'\\b',
'\f':'\\f',
'\\\
' :'\\\\
',
'\r':'\\r',
'\t':'\\t',
}


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).replace('/', r'\/')

reliably works, but it looks hacky.

I know that forward slashes don't have to be escaped, but you may escape them, and for my usecase I'd like to have them escaped.

Is there a way to to let the JSONEncoder escape forward slashes without manually escaping them?

解决方案

Only escape forward slashes when encode_html_chars=True

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

The JSON spec says forward slahes 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 </script> attack
    '/': '\\/',
    '\\': '\\\\',
    '"': '\\"',
    '\b': '\\b',
    '\f': '\\f',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t',
}

这篇关于json.dumps():转义正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆