当我尝试使用json.load()打开时,我有一个1.7 GB的JSON文件然后它给出了内存错误,如何读取python中的json文件?
我的JSON文件是包含特定键的大量对象.
编辑:如果它只是一个大的对象数组,并且事先知道对象的结构,那么就不需要使用我们可以逐行读取的工具.一行只包含数组的一个元素.我注意到这是json文件存储的方式,对我来说它只是工作
>>>for line in open('file.json','r').readline():
... do something with(line)
Run Code Online (Sandbox Code Playgroud) 我希望为一个非常非常大的JSON文件(~1TB)实现流式json解析器,我无法将其加载到内存中.一种选择是使用像https://github.com/stedolan/jq这样的文件将文件转换为json-newline-delimited,但是我需要对每个json对象做各种其他事情,这使得这种方法不理想.
给定一个非常大的json对象,我如何能够逐个对象地解析它,类似于xml中的这种方法:https://www.ibm.com/developerworks/library/x-hiperfparse/index.html.
例如,在伪代码中:
with open('file.json','r') as f:
json_str = ''
for line in f: # what if there are no newline in the json obj?
json_str += line
if is_valid(json_str):
obj = json.loads(json_str)
do_something()
json_str = ''
Run Code Online (Sandbox Code Playgroud)
另外,我没有发现jq -c特别快(忽略内存考虑因素).例如,做json.loads与使用一样快(并且快一点)jq -c.我也试过使用ujson,但一直遇到腐败错误,我认为这与文件大小有关.
# file size is 2.2GB
>>> import json,time
>>> t0=time.time();_=json.loads(open('20190201_itunes.txt').read());print (time.time()-t0)
65.6147990227
$ time cat 20190206_itunes.txt|jq -c '.[]' > new.json
real 1m35.538s
user 1m25.109s
sys 0m15.205s …Run Code Online (Sandbox Code Playgroud)