【问题标题】:convert json to csv without keys and put all values in one row将 json 转换为没有键的 csv 并将所有值放在一行中
【发布时间】:2022-01-26 13:58:33
【问题描述】:

如何从这个 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 中,所有值都应该在一行中...我不需要任何标题或索引。只是价值观

【问题讨论】:

标签: python json pandas csv row


【解决方案1】:

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

【讨论】:

  • 非常感谢。我花了一整天的时间,在这里找不到任何解决方案。 TY
猜你喜欢
  • 2016-06-02
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
相关资源
最近更新 更多