如何将 json 转换为具有单个 header 和多个值的 csv?
How to convert json to csv with single header and multiple values?
我有输入
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.
你几乎完成了你的工作,我认为你不需要使用 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)
我有输入
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.
你几乎完成了你的工作,我认为你不需要使用 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)