【发布时间】:2019-02-07 19:03:29
【问题描述】:
我正在研究一个最终可能会尝试将非常大的 json 数组序列化到文件的过程。因此,将整个数组加载到内存中并仅转储到文件是行不通的。我需要将各个项目流式传输到文件以避免内存不足问题。
令人惊讶的是,我找不到任何这样做的例子。下面的代码 sn-p 是我拼凑起来的。有没有更好的方法来做到这一点?
first_item = True
with open('big_json_array.json', 'w') as out:
out.write('[')
for item in some_very_big_iterator:
if first_item:
out.write(json.dumps(item))
first_item = False
else:
out.write("," + json.dumps(item))
out.write("]")
【问题讨论】:
-
并且大概您需要在以后从文件中加载数据,因此会遇到同样的问题。我想这就是创建换行 json 格式的原因
标签: python json serialization