How to change a value from JSON?

Question:

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?

Asked By: baduan

||

Answers:

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'))
Answered By: NYC Coder

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.

Answered By: Lanre
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.