Search code examples
jsonpython-3.xdictionaryelementaddition

add main attribute to json object in python


I want to add main attribute to json objects. Please see the python code, json objects and expected outcomes below.

data.json

    [{
       "Full Address": "data1",
       "p1": "1",
       "p2": "6"  
      },
      {
      "Full Address": "data2",
      "p1": "1",
      "p2": "6"
    }]

expected outcomes

    [{
    "fields": {
      "Full Address": "data1",
      "p1": "1",
      "p2": "6"
       }
     },
     {
   "fields": {
    "Full Address": "data2",
    "p1": "1",
    "p2": "6"
   }
   }]

code

import json
with open("data.json", 'r') as json_file:
 json_decoded = json.load(json_file)
for x in json_decoded:
 x['fields'] = ''
 with open("output.json", 'w') as json_out_file:
 json.dump(json_decoded, json_out_file, indent=2, ensure_ascii=False)

with this code I am able to add elements inside json objects, but my expected results is different.

output of my code is

   [
     {
      "Full Address": "data1",
      "p1": "1",
      "p2": "6",
      "fields": " "
     },
     {
    "Full Address": "data2",
    "p1": "1",
    "p2": "6",
    "fields": " "
    }
  ]

Picture


Solution

  • Try this:

    import json
    
    d = [
        {
            "Full Address": "data1",
            "p1": "1",
            "p2": "6"
        },
        {
            "Full Address": "data2",
            "p1": "1",
            "p2": "6"
        },
    ]
    
    print(json.dumps([{"fields": {**i}} for i in d], indent=2))
    

    Output:

    [
      {
        "fields": {
          "Full Address": "data1",
          "p1": "1",
          "p2": "6"
        }
      },
      {
        "fields": {
          "Full Address": "data2",
          "p1": "1",
          "p2": "6"
        }
      }
    ]