我正在尝试加载一个大的JSON文件(300MB),用来解析成excel。我刚开始在做json.load(文件)的时候遇到一个MemoryError。类似的问题已经发布,但无法回答我的具体问题。我希望能够像在代码中那样,在一个块中返回json文件中的所有数据。做到这一点的最好方法是什么?Code和json结构如下:
代码如下所示。
def parse_from_file(filename):
""" proceed to load the json file that given and verified,
it and returns the data that was in the json file so it can actually be read
Args:
filename (string): full branch location, used to grab the json file plus '_metrics.json'
Returns:
data: whatever data is being loaded from the json file
"""
print("STARTING PARSE FROM FILE")
with open(filename) as json_file:
d = json.load(json_file)
json_file.close()
return d结构看起来像这样。
[
{
"analysis_type": "test_one",
"date": 1505900472.25,
"_id": "my_id_1.1.1",
"content": {
.
.
.
}
},
{
"analysis_type": "test_two",
"date": 1605939478.91,
"_id": "my_id_1.1.2",
"content": {
.
.
.
}
},
.
.
.
]在“内容”中,信息不一致,但有3个不同但不同的可能模板,可以基于analysis_type进行预测。
发布于 2018-01-12 23:43:36
我确实喜欢这种方式,希望它能对你有所帮助。也许你需要跳过第1行"[“。如果存在"},",则删除行尾的“,”。
with open(file) as f:
for line in f:
while True:
try:
jfile = ujson.loads(line)
break
except ValueError:
# Not yet a complete JSON value
line += next(f)
# do something with jfile发布于 2018-01-12 23:29:12
如果所有经过测试的库都给您带来了内存问题,我的方法是将文件拆分为数组中的每个对象一个。
如果文件像你在操作中所说的那样有换行符和填充,我应该逐行读取,如果是[或],每当你找到一个需要删除逗号的},时,就丢弃它,把行写到新文件。然后尝试加载每个文件,并在结束读取每个文件时打印一条消息,看看哪里失败了。
如果文件没有换行符或者没有正确填充,你需要开始读取字符,当你找到[或{时增加它们,当你找到]或}时减少它们。还要考虑到,您可能需要丢弃字符串中的任何花括号或方括号,尽管这可能不是必需的。
https://stackoverflow.com/questions/48227090
复制相似问题