Reputation: 65
I have two variable which holds a ordered dict and default dict respectively. I want to combine those and form a valid json.
a = OrderedDict([('cat', 80.0), ('dog', 119.07)])
b = defaultdict(<type 'dict'>, {'apple': {'solid': {'NZL': 5032000, 'SHM': 79196000}, 'water':
{'NZL': 1000, 'SHM': 6000}, 'grains': 232000}, 'mango': {'solid': {'ALP': 47283305}, 'water':
{}, 'grains': 330611}})
with open('data.json','w') as file:
json.dump(a, file, indent=5)
file.write('\n')
json.dump(b, file, indent=5)
I want the output as :
[
{
"cat":80.0,
"dog":119.07
},
{
"apple":{
"solid":{
"NZL":5032000,
"SHM":79196000
},
"water":{
"NZL":1000,
"SHM":6000
},
"grains":232000
},
"mango":{
"solid":{
"ALP":47283305
},
"water":{
},
"grains":330611
}
}
]
Anyone help me out with this.
Upvotes: 1
Views: 63
Reputation: 362627
Both OrderedDict
and defaultdict
are already serializable, so you can just do this easily:
with open("data.json", "w") as f:
json.dump([a, b], f, indent=4)
Upvotes: 3