Reputation: 31
how can i convert from this json-format:
{
"Key1": {
"Value": "123",
"Value": "456",
},
"Key2" : {
"Value": "789",
},
"Key3": {
"Value": "000",
},
"Key4" : {
"Value": "111",
}
}
to this csv-format:
|Col A|Col B|Col C|Col D|Col E|
Row 1|123 |456 |789 |000 |111 |
I want to ignore the keys and just add the values to the csv and all values should be in one row...I don´t need any headers or index. just the values
Upvotes: 0
Views: 807
Reputation: 1200
Assuming that the JSON is fixed to be valid, then you can easily do this with a nested list comprehension:
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))
This outputs
['123', '456', '789', '000', '111']
and values.csv
becomes:
123,456,789,000,111
Upvotes: 2