0

I want to merge two JSON files while the data overwrites itself in the main JSON file.

My main object is the following:

{
      "data": [
         {
            "name": "name1",
            "gender": "male",
            "age": "20",
            "subject": "Python",
            "pass": "No"
           }
      ]
    }

"new data.json" needs to be overridden with the following:

 {
  "data": [
     {
        "name": "name1",
        "subject": "Python",
        "pass": "Yes"
       }
  ]
}

The result object should be:

{
  "data": [
     {
        "name": "name1",
        "gender": "male",
        "age": "20",
        "subject": "Python",
        "pass": "Yes"          //updated
       }
  ]
}
0

1 Answer 1

1

In general, you can use the built-in Python update method for dictionaries, which updates the current dictionary with values of a new one while keeping old data present.

For your case (assuming you always need to update the FIRST element in the array within the "data" key):

original_data = {
      "data": [
         {
            "name": "name1",
            "gender": "male",
            "age": "20",
            "subject": "Python",
            "pass": "No"
           }
      ]
    }

new_data =  {
  "data": [
     {
        "name": "name1",
        "subject": "Python",
        "pass": "Yes"
       }
  ]
}

original_data["data"][0].update(new_data["data"][0]) #this updates the original JSON

Sign up to request clarification or add additional context in comments.

1 Comment

This. Was about to ^^ Question: why is the nested dictionary inside a list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.