这将从字符串中解码您的JSON对象“列表”:
from json import JSonDeprerdef loads_invalid_obj_list(s): deprer = JSonDeprer() s_len = len(s) objs = [] end = 0 while end != s_len: obj, end = deprer.raw_depre(s, idx=end) objs.append(obj) return objs
这里的好处是您可以与解析器一起很好地玩。因此,它会不断告诉您 确切 的错误位置。
例子
>>> loads_invalid_obj_list('{}{}')[{}, {}]>>> loads_invalid_obj_list('{}{n}{')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "depre.py", line 9, in loads_invalid_obj_list obj, end = deprer.raw_depre(s, idx=end) File "/System/Library/frameworks/Python.framework/Versions/2.7/lib/python2.7/json/deprer.py", line 376, in raw_depre obj, end = self.scan_once(s, idx)ValueError: Expecting object: line 2 column 2 (char 5)清洁溶液(稍后添加)
import jsonimport re#shameless copy paste from json/deprer.pyFLAGS = re.VERBOSE | re.MULTILINE | re.DOTALLWHITESPACE = re.compile(r'[ tnr]*', FLAGS)class ConcatJSONDeprer(json.JSONDeprer): def depre(self, s, _w=WHITESPACE.match): s_len = len(s) objs = [] end = 0 while end != s_len: obj, end = self.raw_depre(s, idx=_w(s, end).end()) end = _w(s, end).end() objs.append(obj) return objs
例子
>>> print json.loads('{}', cls=ConcatJSONDeprer)[{}]>>> print json.load(open('file'), cls=ConcatJSONDeprer)[{}]>>> print json.loads('{}{} {', cls=ConcatJSONDeprer)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads return cls(encoding=encoding, **kw).depre(s) File "depre.py", line 15, in depre obj, end = self.raw_depre(s, idx=_w(s, end).end()) File "/System/Library/frameworks/Python.framework/Versions/2.7/lib/python2.7/json/deprer.py", line 376, in raw_depre obj, end = self.scan_once(s, idx)ValueError: Expecting object: line 1 column 5 (char 5)


