2

I'm trying to add key value pairs into the existing JSON file. I am able to concatenate to the parent label, How to add value to the child items?

JSON file:

{
  "students": [
    {
      "name": "Hendrick"
    },
    {
      "name": "Mikey"
    }
  ]
}

Code:

import json

with open("input.json") as json_file:
    json_decoded = json.load(json_file)

json_decoded['country'] = 'UK'

with open("output.json", 'w') as json_file:
    for d in json_decoded[students]:
        json.dump(json_decoded, json_file)

Expected Results:

{
  "students": [
    {
      "name": "Hendrick",
      "country": "UK"
    },
    {
      "name": "Mikey",
      "country": "UK"
    }
  ]
}

3 Answers 3

5

You can do the following in order to manipulate the dict the way you want:

for s in json_decoded['students']:
    s['country'] = 'UK'

json_decoded['students'] is a list of dictionaries that you can simply iterate and update in a loop. Now you can dump the entire object:

with open("output.json", 'w') as json_file:
    json.dump(json_decoded, json_file)
Sign up to request clarification or add additional context in comments.

Comments

2
import json

with open("input.json", 'r') as json_file:
    json_decoded = json.load(json_file)

    for element in json_decoded['students']:
        element['country'] = 'UK'

    with open("output.json", 'w') as json_out_file:
        json.dump(json_decoded, json_out_file)
  1. opened a json file i.e. input.json
  2. iterated through each of its element
  3. add a key named "country" and dynamic value "UK", to each element
  4. opened a new json file with the modified JSON.

Edit:

Moved writing to output file inside to first with segment. Issue with earlier implemenation is that json_decoded will not be instantiated if opening of input.json fails. And hence, writing to output will raise an exception - NameError: name 'json_decoded' is not defined

Comments

0

This gives [None, None] but update the dict:

a = {'students': [{'name': 'Hendrick'}, {'name': 'Mikey'}]}
[i.update({'country':'UK'}) for i in a['students']]
print(a)

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.