Reputation: 23
I have a python nested dictionary in the following format
data = {
'item1': {
'name': "A",
'price': 10
},
'item2': {
'name': "B",
'price': 20
}
}
My expected output JSON file will be the following format
[
{
"name": "A",
"price": 10
},
{
"name": "B",
"price": 20
}
]
My code is
data = {
'item1': {
'name': "A",
'price': 10
},
'item2': {
'name': "B",
'price': 20
}
}
with open("my.json", "w") as f:
json.dump(data, f)
But this code can't generate my expected JSON output format, how can i do it?
Upvotes: 0
Views: 3409
Reputation: 116
import json
data = {
'item1': {
'name': "A",
'price': 10
},
'item2': {
'name': "B",
'price': 20
}
}
print(list(data.values()))
json.dump(list(data.values()), f)
Upvotes: 2
Reputation: 707
The problem is not about JSON but about having a dictionary and expecting a list.
You can convert your dictionary entries to a list with list(data.values())
and then export it to JSON.
Upvotes: 2