How to Modify JSON File in Python?

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

In this example, you will learn python read and write to same json file. We will look at an example of append json file in python. We will use python open json file and modify. I would like to show you how to update json file in python. Here, Create a basic example of how to edit a json file in python.

There are several ways to update the JSON file in python. Here, i will give you very simple example of edit JSON file using open(), append(), dump() and close() functions. so let's see a simple example below:

You can use these examples with python3 (Python 3) version.

Example:

I simply created data.json file with content as like below showed you. we will open that file and read it, Then write some more content on it.

data.json

[
  {
    "ID": 1,
    "Name": "Hardik Savani",
    "email": "hardik@gmail.com"
  },
  {
    "ID": 2,
    "Name": "Vimal Kashiyani",
    "email": "vimal@gmail.com"
  },
  {
    "ID": 3,
    "Name": "Harshad Pathak",
    "email": "harshad@gmail.com"
  }
]

main.py

import json
  
# Read Existing JSON File
with open('data.json') as f:
    data = json.load(f)
  
# Append new object to list data
data.append({
        "ID": 4,
        "Name": "Paresh Patel",
        "email": "paresh@gmail.com"
    })
  
# Append new object to list data
data.append({
        "ID": 5,
        "Name": "Rakesh Patel",
        "email": "rakesh@gmail.com"
    })
    
# Create new JSON file
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)
  
# Closing file
f.close()

Output:

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[
  {
    "ID": 1,
    "Name": "Hardik Savani",
    "email": "hardik@gmail.com"
  },
  {
    "ID": 2,
    "Name": "Vimal Kashiyani",
    "email": "vimal@gmail.com"
  },
  {
    "ID": 3,
    "Name": "Harshad Pathak",
    "email": "harshad@gmail.com"
  },
  {
    "ID": 4,
    "Name": "Paresh Patel",
    "email": "paresh@gmail.com"
  },
  {
    "ID": 5,
    "Name": "Rakesh Patel",
    "email": "rakesh@gmail.com"
  }
]

I hope it can help you...

Tags :
Shares