Python使用转义的双引号解析JSON [英] Python parsing JSON with escaped double quotes
本文介绍了Python使用转义的双引号解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑此有效的json:
Consider this valid json:
{"a": 1, "b": "{\"c\":2}"}
当我尝试解析它时,Python的json
模块会抛出-好像\"
正在抛出它:
Python's json
module throws when I try to parse it - it looks like the \"
is throwing it off:
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)
是否可以使用json
模块或诸如ujson
之类的其他模块在Python中解析此内容?
Is there any way to parse this in Python, either using the json
module or some other module like ujson
?
推荐答案
实际上,转义的双引号无关紧要.查看我的测试:
Actually it doesn't matter with escaped double quotes. See my test:
>>> 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}}
>>>
这篇关于Python使用转义的双引号解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文