gpt4 book ai didi

Python:使列表生成器 JSON 可序列化

转载 作者:太空狗 更新时间:2023-10-29 16:59:54 26 4
gpt4 key购买 nike

如何将 JSON 文件列表连接成一个巨大的 JSON 数组?我有 5000 个文件和 550 000 个列表项。

我的第一个尝试是使用 jq ,但看起来 jq -s 并未针对大输入进行优化。

jq -s -r '[.[][]]' *.js 

此命令有效,但需要很长时间才能完成,我真的很想用 Python 解决这个问题。

这是我当前的代码:

def concatFiles(outName, inFileNames):
def listGenerator():
for inName in inFileNames:
with open(inName, 'r') as f:
for item in json.load(f):
yield item

with open(outName, 'w') as f:
json.dump(listGenerator(), f)

我得到:

TypeError: <generator object listGenerator at 0x7f94dc2eb3c0> is not JSON serializable

任何将所有文件加载到 ram 的尝试都会触发 Linux 的 OOM-killer。你有什么想法吗?

最佳答案

从 simplejson 3.8.0 开始,您可以使用 iterable_as_array 选项将任何可迭代序列化为数组

# Since simplejson is backwards compatible, you should feel free to import
# it as `json`
import simplejson as json
json.dumps((i*i for i in range(10)), iterable_as_array=True)

结果是 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

关于Python:使列表生成器 JSON 可序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com