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

标签 python json csv

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

{"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/

相关文章:

python - 将两个字典以及具有相同键的项目添加到一起

jquery - session 超时后,对第一个请求的后续 AJAX post 请求将抛出 InvalidCsrfTokenException

javascript - angular2 - 将 json 文件内容放入我的类属性中

python - 在 Python 中合并 NumPy 数组并查找列

python - 在 Python 中使用 %s 会去除 CSV 到 XML 转换中的前导零

powershell - Powershell行数包含大量文本文件的csv

python - matplotlib中图例中的重复项目?

python - pd.Series.str.contains 的矢量化版本

python - Numpy 索引顺序

mysql - JSON_SET 不更新 MySQL 中的空 JSON 字段