Home > Software engineering >  How to change a value from json in python?
How to change a value from json in python?

Time:08-04

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?

CodePudding user response:

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'))

CodePudding user response:

Hi Baduan you can read json file with pandas library;

import pandas as pd

df = pd.read_json("FILE_JSON.json")

After that you can access and manipulate values for dataframe.

  • Related