gpt4 book ai didi

python - 如何将具有可变长度行的平面 json 文件转换为 csv 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 16:33:58 25 4
gpt4 key购买 nike

这是我拥有的数据的示例。

{"a":"1", "b":"2", "c":"3"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6"}

我希望 csv 为:

a,b,c,d,e,f
1,2,3
1,2,3,4,5
1,2,3,4,5,6

我在线尝试了不同的转换器,但由于 json 文件大约有 10 MB,我无法在线转换它。

最佳答案

import csv
import json

with open('in.json') as infile:
data = json.load(infile)

headers = set()
for row in data:
headers.update(row.keys())

with open('out.csv', 'w') as outfile:
writer = csv.DictWriter(outfile, headers)
writer.writeheader()
writer.writerows(data)

in.json:

[
{"a":"1", "b":"2", "c":"3"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"},
{"a":"1", "b":"2", "c":"3", "d":"4", "e":"5", "f":"6"}
]

out.csv:

a,c,b,e,d,f
1,3,2,,,
1,3,2,5,4,
1,3,2,5,4,6

关于python - 如何将具有可变长度行的平面 json 文件转换为 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366626/

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