繁体   English   中英

在没有键的情况下将 json 转换为 csv 并将所有值放在一行中

[英]convert json to csv without keys and put all values in one row

我怎样才能从这个 json 格式转换:

{
   "Key1": {
       "Value": "123",
       "Value": "456",
   },
   "Key2" : {
       "Value": "789",
   },
   "Key3": {
       "Value": "000",
   },
   "Key4" : {
       "Value": "111",
   }
}

到这个 csv 格式:

     |Col A|Col B|Col C|Col D|Col E|
Row 1|123  |456  |789  |000  |111  |

我想忽略键,只需将值添加到 csv 并且所有值都应该在一行中......我不需要任何标题或索引。 只是价值观

假设 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM