Simplejson 转储 char \

发布于 2024-08-31 07:57:39 字数 281 浏览 2 评论 0原文

我正在使用 Django 进行编程,需要将对象序列化为字符串,但我需要将字符串 \/ 序列化。

一个例子:

simplejson.dumps({'id' : 'root\/leaf'})

我需要这样的输出:

{"id": "root\/leaf"}

但我得到这个:

{"id": "root\\\\\\\\leaf"}

I'm programming with Django need to serialize an object to a string, but I need to get the string \/ serialized.

An example:

simplejson.dumps({'id' : 'root\/leaf'})

I need an output like this:

{"id": "root\/leaf"}

But I get this:

{"id": "root\\\\\\\\leaf"}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话墙 2024-09-07 07:57:39

JSON 要求对文字 \ 字符进行转义,并表示为 \\。 Python 还将转义的文字 \ 字符表示为 \\。在两者之间,\ 变为 \\\\

请注意 Python 中的以下内容:

>>> "\\/" == "\/"
True

>>> {"id": "root\/leaf"} == {"id": "root\\/leaf"}
True

>>> {"id": "root\\/leaf"}["id"]
'root\\/leaf'

>>> print {"id": "root\\/leaf"}["id"]
root\/leaf 

Python 正在打印额外的 escape 。因此,当您执行 simplejson.dumps({"id": "root\/leaf"}) 时,Python 会打印正确的结果 {'id': 'root\\/leaf' },但有额外的 Python 转义,因此 {'id': 'root\\\\/leaf'}。 Python 将每个 \\ 视为单个字符。如果写入文件而不是字符串,您将得到 {'id': 'root\\/leaf'}

编辑:我可能会添加,文字 JSON {"id": "root\/leaf"} 将解码为 {'id': 'root/leaf '},因为文本 JSON \/ 映射到 / 字符。 \// 都是 / 的有效 JSON 编码;似乎没有一种简单的方法可以让 simplejson 使用 \/ 而不是 / 来编码 /

JSON requires that the literal \ character be escaped, and represented as \\. Python also represents the literal \ character escaped, as \\. Between the two of them, \ becomes \\\\.

Notice the following in Python:

>>> "\\/" == "\/"
True

>>> {"id": "root\/leaf"} == {"id": "root\\/leaf"}
True

>>> {"id": "root\\/leaf"}["id"]
'root\\/leaf'

>>> print {"id": "root\\/leaf"}["id"]
root\/leaf 

Python is printing the extra escape . So when you do simplejson.dumps({"id": "root\/leaf"}), python is printing the correct result {'id': 'root\\/leaf'}, but with the extra Python escapes, hence {'id': 'root\\\\/leaf'}. Python regards each \\ as a single character. If you write to a file instead of a string, you'll get {'id': 'root\\/leaf'}.

Edit: I might add, the literal JSON {"id": "root\/leaf"} would decode to {'id': 'root/leaf'}, as the literal JSON \/ maps to the / character. Both \/ and / are valid JSON encodings of /; there doesn't seem to be an easy way to make simplejson use \/ instead of / to encode /.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文