简体   繁体   中英

Merge two json files in python

I have a scenario that i have two json files. lets say fileA.json and fileB.json with some data in both files. In fileA, I have some data and, in fileB I have some changes i need to add in fileA. So after merging both the files, I want it to save data in third file named fileC with same structure and updated data but data should not be loss.

here are my sample files:-

fileA

{  
  "data1":[  
     {  
       "id":"1",
       "name":"abc"
     },
     {  
       "id":"2",
       "name":"xyz"
     }
  ],
 "data2":[  
     {  
       "id":"1",
       "data1_id":"2",
          "data3_ids":[  
              "1"
            ]
     },
     {  
       "id":"2",
       "user_id":"3",
          "data3_ids":[  
              "2"
            ]
     }
  ],
  "data3":[  
     {  
       "id":"1",
       "demo":"pqr",
       "title":"Never Be the Same"
     },
     {  
       "id":"2",
       "demo":"Zedd",
       "title":"The Middle"
     }
  ]
}

fileB

{  
  "data2":[  
    {  
       "id":"1",
       "data1_id":"2",
          "data3_ids":[  
               "1",
               "2"
           ]
    }
  ]
}

I want to update fileA with fileB at same place where data2 is present but with updated value "2" in data2_ids.

Here is my code i have tried:-

import json

with open("fileA.json") as fo:
      data1 = json.load(fo)

with open("fileB.json") as fo:
      data2 = json.load(fo)

data1.update(data2)

with open("fileC.json", "w") as fo:
      json.dump(data1, fo)

The issue i am facing with this code is that although i am getting data of fileB but loosing data of fileA. Can anyone suggest me some solution.

Can't comment. Hence posting an answer. Have you tried jsonmerge?

base = {
    "foo": 1,
    "bar": [ "one" ],
 }

head = {
     "bar": [ "two" ],
     "baz": "Hello, world!"
 }


from jsonmerge import merge
result = merge(base, head)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM