我正在尝试加载一个大文件(大小为2GB),该文件由JSON字符串填充,用换行符分隔。例如:
{
"key11": value11,
"key12": value12,
}
{
"key21": value21,
"key22": value22,
}
…
我现在导入它的方式是:
content = open(file_path, "r").read()
j_content = json.loads("[" + content.replace("}\n{", "},\n{") + "]")
这看起来像是一个技巧(在每个JSON字符串之间添加逗号,以及一个开始方括号和结束方括号,使其成为一个正确的列表)。
有没有更好的方法来指定JSON分隔符(换行符\n
而不是逗号,
)?
而且,Python
似乎无法为从2GB数据构建的对象正确分配内存,在我逐行读取文件时,是否有方法构造每个JSON
对象?谢谢!
这将适用于您提供的特定文件格式。如果格式更改,则需要更改分析行的方式。
只需逐行阅读,并在运行时构建JSON块:
如果您对解析一个非常大的JSON文件而不将所有内容保存到内存感兴趣,那么您应该查看JSON.load API中的object_hook或object_pairs_hook回调方法。
此时只需读取每一行并构造一个json对象:
这样,您就可以加载正确的完整json对象(前提是json值中的某个地方或json对象的中间没有
\n
),并且避免了内存问题,因为每个对象都是在需要时创建的。还有一个答案
https://stackoverflow.com/a/7795029/671543
相关问题 更多 >
编程相关推荐