您几乎可以肯定没有正确定义转义的反斜杠。如果您正确定义字符串,JSON 解析就好了:
>>> import json
>>> json_str = r'''
... {
... "publisher": "\"O'Reilly Media, Inc.\""
... }
... ''' # raw string to prevent the \" from being interpreted by Python
>>> json.loads(json_str)
{u'publisher': u'"O\'Reilly Media, Inc."'}
请注意,我使用原始字符串文字来定义 Python 中的字符串;如果我不这样做,\"
将由 Python 解释并"
插入一个正则。否则,您必须将反斜杠加倍:
>>> print '\"'
"
>>> print '\\"'
\"
>>> print r'\"'
\"
将解析后的 Python 结构重新编码回 JSON 会显示反斜杠重新出现,repr()
字符串的输出使用相同的双反斜杠:
>>> json.dumps(json.loads(json_str))
'{"publisher": "\\"O\'Reilly Media, Inc.\\""}'
>>> print json.dumps(json.loads(json_str))
{"publisher": "\"O'Reilly Media, Inc.\""}
如果您没有逃脱\
转义,您将得到未转义的引号:
>>> json_str_improper = '''
... {
... "publisher": "\"O'Reilly Media, Inc.\""
... }
... '''
>>> print json_str_improper
{
"publisher": ""O'Reilly Media, Inc.""
}
>>> json.loads(json_str_improper)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 3 column 20 (char 22)
请注意,\"
序列现在打印为"
,反斜杠消失了!