0

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

1
  • You don't update the json. You read the json into a dict, update the dict, then use that to completely rewrite the json file. Both questions you linked have the correct answer. Commented Sep 19, 2022 at 13:13

2 Answers 2

1

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

Comments

1

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)

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.