繁体   English   中英

在 Python 中将大文件 JSON 转换为换行符分隔的 JSON

[英]Convert a large file JSON into newline delimited JSON in Python

我尝试将 JSON 文件转换为 ndJSON,以便可以将其上传到 GCS 并将其写入 BQ 表。 我已经在这里尝试了所有方法, 在 Python 中将 JSON 转换为换行符分隔的 JSON,但在我的情况下不起作用,因为我有一个 7GB 的 JSON 文件。

我尝试使用这个 python 代码

import json

with open("input.json", "r") as read_file:
    data = json.load(read_file)
result = [json.dumps(record) for record in data]
with open('nd-output.json', 'w') as obj:
    for i in result:
        obj.write(i+'\n')

但它提出了

Traceback (most recent call last):
  File "my_py_file.py", line 4, in <module>
    data = json.load(read_file)
  File "/usr/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

然后我尝试了jq方法但仍然没有运气

cat input.json | jq -c '.[]'

它提出了

1477 broken pipe  cat input.json |
1478 killed       jq -c '.[]'

我能做些什么来实现我的目标吗?

从报错信息中很明显你得到的错误与系统内存的可用性有关。与其将整个json文件加载到内存中,你可以一次加载一小部分数据,然后你可以加载下一部分和很快。 请参考下面的代码。 在这段代码中,包ijson用于将 json 部分转换为 ndjson。 另外,请注意 Google 并未正式支持ijson

import ijson
 
with open('nd-output.json', 'w') as writefile:
   with open('input.json', 'r') as data:
       for obj in ijson.items(data, 'item'):
           writefile.write(str(obj)+'\n')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM