【问题标题】:Converting list of json objects with different headers to csv将具有不同标头的 json 对象列表转换为 csv
【发布时间】:2021-08-04 13:46:15
【问题描述】:

我有一个如下所示的 json 对象列表:

{
  "a": 1,
  "b": 2,
  "c": 3
},
{
  "a": 5,
  "b": 6,
  "c": 7,
  "d": 8
},
{
  "a": 9,
  "b": 10 
}

我想通过它并将其转换为 csv。问题是许多对象的标题不一致。我希望 csv 文件的标题成为具有最多键的对象的键。如果其中一个对象缺少键,则它在 csv 文件中可能为空。

输出:

a,b,c,d
1,2,3,null
5,6,7,8
9,10,null,null

【问题讨论】:

  • 您是否已经尝试过?
  • 是的,我做到了。我能够获取 csv 文件的标题,但我在处理对象缺少的键背后的逻辑时遇到了问题。我能想到的唯一解决方案是嵌套 3 个 for 循环,但这听起来很糟糕。
  • 我的回答能解决你的问题吗?
  • 您应该将您的尝试与您的问题一起发布。

标签: python json csv


【解决方案1】:

假设变量dicts 将您的输入数据存储为:

dicts = [{
  "a": 1,
  "b": 2,
  "c": 3
},
{
  "a": 5,
  "b": 6,
  "c": 7,
  "d": 8
},
{
  "a": 9,
  "b": 10 
}]
# First we accumulate the values for all so-called headers in the dicts that have them
acc = {} # keys are the headers, values are integer-keyed dicts that act as sparse arrays representing the index of a dict and the value it held for that header
for i, d in enumerate(dicts):
    for k, v in d.items():
        if k not in acc:
            acc[k] = {}

        acc[k][i] = v

# Now we gather the accumulated values for all the headers into a linear format that can be dumped to a .csv
headers = list(acc.keys()) # in an arbitrary order

dump = [headers]
for i in range(len(dicts)):
    row = []
    for h in headers:
        if i in acc[h]: # if the ith dict had a value for this header
            row.append(acc[h][i])
        else:
            row.append("null")

    dump.append(row)

用法:

for line in dump:
    print(line)

输出:

['a', 'b', 'c', 'd']
[1, 2, 3, 'null']
[5, 6, 7, 8]
[9, 10, 'null', 'null']

要将其写入.csv 文件,您可以这样做:

with open('myfile.csv','w') as f:
    for line in dump:
        for item in line:
            f.write(item + ',')
        f.write('\n')

myfile.csv

a,b,c,d
1,2,3,null
5,6,7,8
9,10,null,null

.csv 转储代码取自此 SO 答案:https://stackoverflow.com/a/28863461/12109043

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2021-10-29
    • 2021-12-28
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多