Skip to content
Advertisement

How to merge json string and give new alias and remove old key in Python

I have Some of the data that have nested attribute and need to combine and give new alias also remove the old one.

Sample Data:

[
   {
      "model.code":{
         "model":{
            "code":"Z15"
         }
      }
   },
   {
      "model.name":{
         "model":{
            "name":"Test"
         }
      }
   }
]

Expected Output:

[
   {
      "model":{
         "code":"Z15",
         "name":"Test"
      }
   }
]

How can acheived this using python

Advertisement

Answer

You can solve this by using jsonmerge:

from jsonmerge import merge

d1 ={
      "model.code":{
         "model":{
            "code":"Z15"
         }
      }
   }
d2 = {
      "model.name":{
         "model":{
            "name":"Test"
         }
      }
   }

result = merge(d1["model.code"], d2["model.name"])
>>> result
{'model': {'code': 'Z15', 'name': 'Test'}}

for more complex use cases check Project Description.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement