【问题标题】:How to convert json to csv with single header and multiple values?如何将 json 转换为具有单个标头和多个值的 csv?
【发布时间】:2020-09-08 04:04:10
【问题描述】:

我有输入

data = [
  {
    "details": [
      {
        "health": "Good",
        "id": "1",
        "timestamp": 1579155574
      },
      {
        "health": "Bad",
        "id": "1",
        "timestamp": 1579155575
      }
    ]
  },
  {
    "details": [
      {
        "health": "Good",
        "id": "2",
        "timestamp": 1588329978
      },
      {
        "health": "Good",
        "device_id": "2",
        "timestamp": 1588416380
      }
    ]
  }
]

现在我想将其转换为 csv 格式,如下所示,

id,health
1,Good - 1579155574,Bad - 1579155575
2,Good - 1588329978,Good - 1588416380

这可能吗? 目前我正在将其转换为简单的 csv,我的代码和响应如下,

f = csv.writer(open("test.csv", "w", newline=""))

f.writerow(["id", "health", "timestamp"])
for data in data:
        for details in data['details']:
            f.writerow([details['id'],
                        details["health"],
                        details["timestamp"],
                        ])

回复:

id,health,timestamp
1,Good,1579155574
1,Bad,1579155575
2,Good,1579261319
2,Good,1586911295

那么我怎样才能得到预期的输出呢?我正在使用python3。

【问题讨论】:

    标签: json python-3.x csv jsonconvert


    【解决方案1】:

    你几乎完成了你的工作,我认为你不需要使用 csv 模块。

    而 CSV 没有任何意义,它只是一个名称,让人们知道它是什么。 CSV ,TXT 和 JSON 对计算机来说是一样的东西,它们是用来记录文字的东西。

    我不知道你数据的全部模式,但你可以得到你想要的输出值。

    output = 'id,health\n'
    for data in datas:
        output += f'{data["details"][0]["id"]},'
        for d in data["details"]:
            if 'health' in d:
                output += f'{d["health"]} - {d["timestamp"]},'
            else:
                output += f'{d["battery_health"]} - {d["timestamp"]},'
        output = output[:-1] + '\n'
    
    with open('test.csv', 'w') as op:
       op.write(output)
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 2019-08-21
      • 2014-04-06
      • 1970-01-01
      • 2015-11-20
      • 2019-11-01
      • 2018-11-14
      • 2021-12-28
      相关资源
      最近更新 更多