内容简介:http://stackoverflow.com/questions/20400818/python-trying-to-deserialize-multiple-json-objects-in-a-file-with-each-object-s
好的,经过近一个星期的研究,我打算给他一枪.我有一个文本文件如下(显示3个单独的json对象作为一个例子,但文件有这些的50K):
{ "zipcode":"00544", "current":{"canwc":null,"cig":7000,"class":"observation"}, "triggers":[178,30,176,103,179,112,21,20,48,7,50,40,57] } { "zipcode":"00601", "current":{"canwc":null,"cig":null,"class":"observation"}, "triggers":[12,23,34,28,100] } { "zipcode":"00602", "current":{"canwc":null,"cig":null,"class":"observation"}, "triggers":[13,85,43,101,38,31] }
我知道如何使用Python json库来处理JSON对象,但是我对如何从读取文件创建5万个不同的json对象有一个挑战. (也许我甚至没有正确地考虑这个问题,但最终我需要反序列化和加载到一个数据库)我已经尝试了itertools认为我需要一个生成器,所以我能够使用:
with open(file) as f: for line in itertools.islice(f, 0, 7): #since every 7 lines is a json object jfile = json.load(line)
但是上面显然不会工作,因为它不是将7行作为一个单独的json对象读取,而且我也不知道如何在整个文件中迭代并加载个别的json对象.
以下将给我一个列表我可以切片:
list(open(file))[:7]
任何帮助将非常感激.
非常接近我所需要的,我认为只有一步之遥,但仍然挣扎着一点点迭代.这将最终让我对所有数据帧进行反复打印,但是如何使其能够捕获一个巨大的数据帧,所有这些数据框都是基本连接的?那么我可以将最终的数据帧导出到csv等(还有更好的方式将这个结果上传到一个数据库中,而不是先创建一个巨大的数据框?)
def lines_per_n(f, n): for line in f: yield ''.join(chain([line], itertools.islice(f, n - 1))) def flatten(jfile): for k, v in jfile.items(): if isinstance(v, list): jfile[k] = ','.join(v) elif isinstance(v, dict): for kk, vv in v.items(): jfile['%s' % (kk)] = vv del jfile[k] return jfile with open('deadzips.json') as f: for chunk in lines_per_n(f, 7): try: jfile = json.loads(chunk) pd.DataFrame(flatten(jfile).items()) except ValueError, e: pass else: pass
加载6个额外的行代替,并将该字符串传递给json.loads():
with open(file) as f: for line in f: # slice the next 6 lines from the iterable, as a list. lines = [line] + list(itertools.islice(f, 6)) jfile = json.loads(''.join(lines)) # do something with jfile
json.load()将不仅仅是文件中的下一个对象,而islice(f,0,7)将只读取前7行,而不是读取7行数据块中的文件.
您可以在生成器中包装读取大小为N的文件:
from itertools import islice, chain def lines_per_n(f, n): for line in f: yield ''.join(chain([line], itertools.islice(f, n - 1)))
然后使用它来块输入文件:
with open(file) as f: for chunk in lines_per_n(f, 7): jfile = json.loads(chunk) # do something with jfile
或者,如果你的块变得长度不等,直到有分析结果为止:
with open(file) as f: for line in f: while True: try: jfile = json.loads(line) break except ValueError: # Not yet a complete JSON value line += next(f) # do something with jfile
http://stackoverflow.com/questions/20400818/python-trying-to-deserialize-multiple-json-objects-in-a-file-with-each-object-s
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Discrete Mathematics and Its Applications
Kenneth H Rosen / McGraw-Hill Science/Engineering/Math / 2003-04-22 / USD 132.81
Discrete Mathematics and its Applications is a focused introduction to the primary themes in a discrete mathematics course, as introduced through extensive applications, expansive discussion, and deta......一起来看看 《Discrete Mathematics and Its Applications》 这本书的介绍吧!
MD5 加密
MD5 加密工具
Markdown 在线编辑器
Markdown 在线编辑器