0

我有输入

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。

4

1 回答 1

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)
于 2020-05-21T14:14:29.693 回答