0

当文本中有 " 时,如何使 Python 正确解析 JSON?

json_data = """{
  "*": {
    "picker": {
      "old": 49900,
      "description": "Meaning \"sunshine\" and \r\n- cm."
    }
  }
}"""
clean_json = json_data.replace("\r","").replace("\n","")
print(clean_json)
data_dict = json.loads(clean_json)
pprint(data_dict)

如果我这样做了,.replace("\"","")那么它将匹配"JSON 中的所有内容,这也不起作用。

请帮忙!

4

2 回答 2

3

由于您将 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.'}}}
于 2020-08-07T05:43:56.290 回答
0

我想你需要r在字符串之前添加一个前缀

import json

json_data = r"""
{
    "*": {
        "picker": {
            "old": 49900,
            "description": "Meaning \"sunshine\" and \r\n- cm."
        }
    }
}
"""

clean_json = json_data.replace(r"\r","").replace(r"\n","").replace(r'\"',"")
print(clean_json)
data_dict = json.loads(clean_json)
print(data_dict)

输出是

{
    "*": {
        "picker": {
            "old": 49900,
            "description": "Meaning sunshine and - cm."
        }
    }
}

{'*': {'picker': {'old': 49900, 'description': 'Meaning sunshine and - cm.'}}}
于 2020-08-07T05:58:29.733 回答