这是我拥有的数据的示例。
{"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/