Home > Blockchain >  Update & Add (keys, values) pairs of dictionary in JSON File using python
Update & Add (keys, values) pairs of dictionary in JSON File using python

Time:09-19

I am trying to update,add key,value pairs of dict into JSON File.

JSON File- hi.json

{
    "site_post": {
            "site_name":"test site",
            "location" : "test location",
            "latitude": "123.23",
            "longitude": "456.23"
                },  
    "plant_post": {
         "plant_name" : "plant test",
          "site_id" : "",
          "plant_id": ""
          }
}
import json
with open('hi.json') as f:
    data = json.load(f)

dct = {"site_id":"123","plant_id":"456"}

Expected Output- hi.json

{
    "site_post": {
            "site_name":"test site",
            "location" : "test location",
            "latitude": "123.23",
            "longitude": "456.23",
            "site_id" : "123"
                },  
    "plant_post": {
         "plant_name" : "plant test",
          "site_id" : "123",
          "plant_id": "456"
          }
}

I checked using below posts, but didn't find expected ans. Ref link-

Update Key Value In Python In JSON File

Python JSON add Key-Value pair

CodePudding user response:

You need to update data dictionary and write back to the file

dct = {"site_id": "123", "plant_id": "456"}

with open('hi.json', 'r') as f:
    data = json.load(f)
    data['site_post']['site_id'] = dct['site_id']
    data['plant_post']['site_id'] = dct['site_id']
    data['plant_post']['plant_id'] = dct['plant_id']

with open('hi.json', 'w') as f:
    json.dump(data, f, indent=4)

hi.json:

{
    "site_post": {
        "site_name": "test site",
        "location": "test location",
        "latitude": "123.23",
        "longitude": "456.23",
        "site_id": "123"
    },
    "plant_post": {
        "plant_name": "plant test",
        "site_id": "123",
        "plant_id": "456"
    }
}

CodePudding user response:

I would split dct into two variables or use get to receive what you need, use .update() to update your dict and then write it to hi.json using json.dump

import json
with open('hi.json') as f:
    data = json.load(f)

update_site_post = {"site_id": "123"}
update_plant_post = {"plant_id": "456"}
data.get("site_post").update(update_site_post)
data.get("plant_post").update(update_plant_post)

with open('hi.json', 'w') as f:
    json.dump(data, f)
  • Related