Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change a value from json in python?

I have a JSON file in my hand like this:

{
  "users": [
    {
      "userid": 1,
      "age": 40,
      "name": "Edgar Allan Poe"
    },
    {
      "userid": 2,
      "age": 25,
      "name": "John Keats"
    }
  ]
}

And I want to change user 2’s age, how can I change it from 25 to 26?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the json library:

import json


data = json.load(open('test.json'))
for user in data['users']:
    if user['userid'] == 2:
        user['age'] = 26
json.dump(data, open('test.json', 'w'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading