Python用转义的双引号解析JSON

考虑这个有效的json:

{"a": 1, "b": "{"c":2}"}

当我试图解析它时,Python的json模块会抛出 - 它看起来像"扔掉它:

json.loads('{"a": 1, "b": "{"c":2}"}')
Traceback (most recent call last):
  File "", line 1, in 
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 15 (char 14)

有没有什么办法在Python中解析这个,或者使用json模块或者像ujson这样的其他模块?


其实这与双引号的逃脱无关。 看我的测试:

>>> json.loads('{"a": 1, "b": "{"c":2}"}')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.4/json/decoder.py", line 359, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting ',' delimiter: line 1 column 18 (char 17)

>>> json.loads('{"a": 1, "b": "{"c":2}"}')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.4/json/decoder.py", line 359, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting ',' delimiter: line 1 column 18 (char 17)

>>> json.loads('{"a": 1, "b": {"c":2}}')
{'a': 1, 'b': {'c': 2}}

>>> json.loads('{"a": 1, "b": {"c":2}}')
{'a': 1, 'b': {'c': 2}}

>>> 

在引用的字符串中,“ "与普通引号的处理方式相同:

>>> '{"a": 1, "b": "{"c":2}"}'
'{"a": 1, "b": "{"c":2}"}'

因此,您的字符串不是有效的JSON。

您还需要跳过反斜杠,以便将它们发送到loads 。 你可以通过dumps编码你想要的字典来看到这一点:

>>> json.dumps({"a": 1, "b": "{"c": 2}"})
'{"a": 1, "b": "{"c": 2}"}'

>>> json.loads('{"a": 1, "b": "{"c": 2}"}')
{u'a': 1, u'b': u'{"c": 2}'}
链接地址: http://www.djcxy.com/p/48677.html

上一篇: Python parsing JSON with escaped double quotes

下一篇: How do I automatically fix an invalid JSON string?