由于您将 JSON 嵌入到 Python 字符串文字中,因此当 Python 代码和字符串文字被解析时,它首先应用 Python 的转义规则。
含义首先\"
在 Python 级别解释产生一个单"
,然后这个单"
被解析为 JSON 并失败。
您需要:
- 转义
\
,使其被正确解释为\
结果字符串中的实际字符(只需加倍)
- 或使用rawstrings(只需在三引号字符串前加上
\
),这将禁用大多数转义,它通常用于正则表达式字符串文字,因为它们使用\
很多,但它们也适用于 JSON 字符串文字和其他嵌入
你的版本:
>>> loads("""{
... "*": {
... "picker": {
... "old": 49900,
... "description": "Meaning \"sunshine\" and \r\n- cm."
... }
... }
... }""")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 5 column 32 (char 78)
逃脱逃脱:
>>> loads("""{
... "*": {
... "picker": {
... "description": "Meaning \\"sunshine\\" and \\r\\n- cm."
... }
... }
... }""")
{'*': {'picker': {'description': 'Meaning "sunshine" and \r\n- cm.'}}}
原始字符串:
>>> loads(r"""{
... "*": {
... "picker": {
... "description": "Meaning \"sunshine\" and \r\n- cm."
... }
... }
... }""")
{'*': {'picker': {'description': 'Meaning "sunshine" and \r\n- cm.'}}}