部分网站的返回的json可能未对其中的反斜杠做正确的转义,导致json解析失败。例如:
>>> json.loads(r'[1,"1\,)"]')
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
json.loads(r'[1,"1\,)"]')
File "C:\Users\Jerrism\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\Jerrism\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Jerrism\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid \escape: line 1 column 6 (char 5)
下面是规范的json写法:
>>> json.dumps([1,"1\,)"])
'[1, "1\\\\,)"]'
所以必须对字符串中的反斜杠做转义处理,即替换为双反斜杠。而这些json中可能还包含其它被正确的用于转义的反斜杠,例如\u
,\"
,\\
,替换时需要对其做区分。
>>> json.loads(re.sub(r'(?<!\\)((\\\\)*)\\(?![u\\"])', r'\g<1>\\\\',r'[1,"\,\\,\\\,\u002f,\""]'))
[1, '\\,\\,\\\\,/,"']