栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从文本文件中检索JSON对象(使用Python)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从文本文件中检索JSON对象(使用Python)

这将从字符串中解码您的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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号