KaverappaKU
KaverappaKU

Reputation: 65

Combine a Ordereddict and default dict and dump it in a json file

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

Answers (1)

wim
wim

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

Related Questions