Python JSON add Key-Value pair

10,815

Solution 1

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)

Solution 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

Share:
10,815

Related videos on Youtube

Karthik
Author by

Karthik

Updated on June 04, 2022

Comments

  • Karthik
    Karthik almost 2 years

    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"
        }
      ]
    }