0

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

1 Answer 1

1

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"
    }
  }
]
Sign up to request clarification or add additional context in comments.

Comments

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.