将 json 转换为不带键的 csv 并将所有值放在一行中
convert json to csv without keys and put all values in one row
我如何从这个 json-format:
转换
{
"Key1": {
"Value": "123",
"Value": "456",
},
"Key2" : {
"Value": "789",
},
"Key3": {
"Value": "000",
},
"Key4" : {
"Value": "111",
}
}
到这个csv-format:
|Col A|Col B|Col C|Col D|Col E|
Row 1|123 |456 |789 |000 |111 |
我想忽略键,只将值添加到 csv 中,所有值都应该在一行中...我不需要任何 headers 或索引。只是值
假设 JSON 固定为有效,那么您可以使用嵌套列表理解轻松地做到这一点:
data = {
"Key1": {
"Value1": "123", # Note: I've fixed your JSON here.
"Value2": "456",
},
"Key2": {
"Value1": "789",
},
"Key3": {
"Value1": "000",
},
"Key4": {
"Value1": "111",
},
}
# In practice this might be in a different data.json file,
# which can then be opened with:
# import json
# with open("data.json", "r") as f:
# data = json.load(f)
# Take the values of the outer dict, and then the values of the inner dict
values = [value for value_dict in data.values() for value in value_dict.values()]
print(values)
# Write to a file by separating with commas
with open("values.csv", "w") as f:
f.write(",".join(values))
这输出
['123', '456', '789', '000', '111']
和 values.csv
变为:
123,456,789,000,111
我如何从这个 json-format:
转换{
"Key1": {
"Value": "123",
"Value": "456",
},
"Key2" : {
"Value": "789",
},
"Key3": {
"Value": "000",
},
"Key4" : {
"Value": "111",
}
}
到这个csv-format:
|Col A|Col B|Col C|Col D|Col E|
Row 1|123 |456 |789 |000 |111 |
我想忽略键,只将值添加到 csv 中,所有值都应该在一行中...我不需要任何 headers 或索引。只是值
假设 JSON 固定为有效,那么您可以使用嵌套列表理解轻松地做到这一点:
data = {
"Key1": {
"Value1": "123", # Note: I've fixed your JSON here.
"Value2": "456",
},
"Key2": {
"Value1": "789",
},
"Key3": {
"Value1": "000",
},
"Key4": {
"Value1": "111",
},
}
# In practice this might be in a different data.json file,
# which can then be opened with:
# import json
# with open("data.json", "r") as f:
# data = json.load(f)
# Take the values of the outer dict, and then the values of the inner dict
values = [value for value_dict in data.values() for value in value_dict.values()]
print(values)
# Write to a file by separating with commas
with open("values.csv", "w") as f:
f.write(",".join(values))
这输出
['123', '456', '789', '000', '111']
和 values.csv
变为:
123,456,789,000,111