需要一种在Python中加载嵌入的,转义的JSON字符串的方法

时间:2014-02-12 15:52:27

标签: python json

我必须解析以下JSON字符串:

{"JobDescription":"{\"project\": \"1322\", \"vault\": \"qa-122\"}"}'

如果我尝试使用json.loads,我会得到以下内容:

>>> import json
>>> print json.loads('{"JobDescription":"{\"project\": \"1322\", \"vault\": \"qa-122\"}"}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
 File "/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 "/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 22 (char 21)

我对其收到的字符串没有任何控制权,因为它是由另一个系统生成的。

1 个答案:

答案 0 :(得分:3)

您不会生成嵌入式反斜杠; Python将\"解释为转义引号,最终字符串只包含引号:

>>> '{"JobDescription":"{\"project\": \"1322\", \"vault\": \"qa-122\"}"}'
'{"JobDescription":"{"project": "1322", "vault": "qa-122"}"}'

使用原始字符串或双斜线:

>>> r'{"JobDescription":"{\"project\": \"1322\", \"vault\": \"qa-122\"}"}'
'{"JobDescription":"{\\"project\\": \\"1322\\", \\"vault\\": \\"qa-122\\"}"}'
>>> '{"JobDescription":"{\\"project\\": \\"1322\\", \\"vault\\": \\"qa-122\\"}"}'
'{"JobDescription":"{\\"project\\": \\"1322\\", \\"vault\\": \\"qa-122\\"}"}'

然后加载正常:

>>> import json
>>> json.loads('{"JobDescription":"{\\"project\\": \\"1322\\", \\"vault\\": \\"qa-122\\"}"}')
{u'JobDescription': u'{"project": "1322", "vault": "qa-122"}'}
>>>