Python >= 2.7.15 似乎产生与 Python3 相同的错误消息:
test = """
{
"host":"1.2.3.4",
"user":"abc",
"passwd":"s&]\yz$&u42/",
"dbname":"sample",
"port":2341
}
"""
print json.loads(test)
错误:
ValueError: Invalid \escape: line 5 column 16 (char 54)
稍微修改@Zero Piraeus's代码使其在Python2.7下工作:
import json
import re
def permissive_json_loads(text):
_rePattern = re.compile(r'''(\d+)\)$''', re.MULTILINE)
i = 0
# Make sure the loop is going to terminate.
# There wont be more iterations than the double amout of characters
while True:
i += 1
if i > len(text) * 2:
return
try:
data = json.loads(text)
except ValueError, exc:
exMsg = str(exc)
if exMsg.startswith('Invalid \\escape'):
m = re.search(_rePattern, exMsg)
if not m:
return
pos = int(m.groups()[0])
print "Replacing at: %d" % pos
text = text[:pos] + '\\' + text[pos:]
else:
raise
else:
return data
text = """
{
"host":"1.2.3.4",
"user":"abc",
"passwd":"s&]\yz$&u42/",
"dbname":"sample",
"port":2341
}
"""
i = permissive_json_loads(text)
print i
打印:
Replacing at position: 54
{u'passwd': u's&]\\yz$&u42/', u'host': u'1.2.3.4', u'port': 2341, u'user': u'abc', u'dbname': u'sample'}