【发布时间】:2022-01-12 23:03:22
【问题描述】:
我正在解析一个包含对象数组的大型 JSON 文件,并将数据写入 Python 中的 csv 文件。 JSON 文件大小为 50GB,加载文件时出现内存错误 (data = json.load(data_file))。
当我以大约 4GB 及以下的文件大小运行时,代码运行成功。当我以 50 GB 或更大的文件大小运行时,如何解决内存错误?
JSON 文件结构:
[
{"name":"Haks",
"age":"22",
"other":{
"weight":"100"
}
},
{"name":"Kahs",
"age":"38"
"other":{
"weight":"120"
}
},
.....
]
代码:
import json
import csv
with open('C:/Users/username/filename.json') as data_file
data = json.load(data_file)
arr = []
for x in data:
obj = []
obj['name'] = x['name']
obj['age'] = x['age']
obj['weight']= x['other']['weight']
arr.append(obj)
keys = arr[0].keys()
with open('json_output.csv', 'w',newline='') as csvfile:
writer = csv.DictWriter(csvfile, keys)
writer.writeheader()
for item in arr:
writer.writerow(item)
【问题讨论】:
-
对象的“列表”,而不是 Python 术语中的数组。
标签: python json pandas parsing data-analysis