如何在Python中使用JSON库解码JSON并忠实地表示反斜杠

2024-06-03 01:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个配置文件,我试图拆开,然后用更新的部分重新组装。配置文件是json格式的,我试图在插入到另一个json文件之前提取其中的组件进行更新。在

我发现的问题是JSON文件的部分使用"\/",当使用python的JSON库解码时,我得到"/"。一旦将更新的值插入新的JSON文件中,我需要忠实地表示原始JSON,因此我需要缺少的"\/"。在

我怀疑\被解释为转义,并被JSON解码器丢弃。在

以下是我迄今为止所做努力的一个例子:

JSON字符串示例:

{"Markup\/0.xaml":"text\/xml; charset=utf-8; format=xml; clrtype=ESRI.ArcGIS.Client.Graphic","Markup\/1.xaml":"text\/xml; charset=utf-8; format=xml; clrtype=ESRI.ArcGIS.Client.Graphic"}

Python代码:

^{pr2}$

打印结果:

u'Markup/0.xaml': u'text/xml; charset=utf-8; format=xml; clrtype=ESRI.ArcGIS.Client.Graphic',
u'Markup/1.xaml': u'text/xml; charset=utf-8; format=xml; clrtype=ESRI.ArcGIS.Client.Graphic'

Tags: 文件textclientjsonformat配置文件xmlutf
1条回答
网友
1楼 · 发布于 2024-06-03 01:00:40

是的,\反斜杠是转义字符,正确的JSON解码器会将这种字符视为转义。pythonjson解码器也不例外。见section 7 of RFC 7159

Any character may be escaped.

以及

char = unescaped /
    escape (
        %x22 /          ; "    quotation mark  U+0022
        %x5C /          ; \    reverse solidus U+005C
        %x2F /          ; /    solidus         U+002F
        %x62 /          ; b    backspace       U+0008
        %x66 /          ; f    form feed       U+000C
        %x6E /          ; n    line feed       U+000A
        %x72 /          ; r    carriage return U+000D
        %x74 /          ; t    tab             U+0009
        %x75 4HEXDIG )  ; uXXXX                U+XXXX

escape = %x5C              ; \

(所以\/序列是escape solidus序列)。在

您的输出是正确的;因为我希望像text和{}这样的mimetype组件由正斜杠分隔,而不是由\/分隔。在

然而,正斜杠(标准中的索里达)没有可以转义。相同的第7节说明了哪些字符必须转义:

All Unicode characters may be placed within the quotation marks, except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

因此,pythonjson编码器在生成JSON输出时不会转义正斜杠。在

相关问题 更多 >