JSON对象被打印到我的syslog文件中。我需要从日志中提取字符串并将其转换为JSON。我在提取“{”和“}”之间的字符串时没有任何问题,但是某些字符串中有转义符,这会导致json.loads失败
问题是:>>> import json
>>> resp = '{"from_hostname": {"value": "mysite.edu\"", "value2": 0, "value3": 1}}'
>>> json.loads(resp)
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 41 (char 40)
>>> resp[40]
'"'
>>> resp[41]
','
>>> resp[39]
'"'
>>>
当json看到\"时,我猜它只看到",并假设字符串结束,它抛出分隔符错误。
我试着用\\"替换\",但这似乎不起作用。
注意:\"可以出现在字符串的开头、结尾或中间。
我怎样才能让这工作?