Consider this valid json:
{"a": 1, "b": "{\"c\":2}"}
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)
Is there any way to parse this in Python, either using the json
module or some other module like ujson
?
Inside a quoted string,
\"
is treated the same as a regular quote:As a result, your string is not valid JSON.
You need to escape the backslashes as well, so that they are sent to
loads
. You can see this by encoding your desired dictionary withdumps
:Actually it doesn't matter with escaped double quotes. See my test: