Python Modify JSON File Tutorial

Published On: 23/01/2023 | Category: Python


Hi Dev,

In this example we will go over the demonstration of modify json file in python. This article goes in detailed on python read and write to same json file. you can see python open json file and modify. I would like to show you how to edit a json file python. Follow bellow tutorial step of python json update value by key.

Here, i will describe you example of edit JSON file using open(), append(), dump() and close() functions. so let's see a simple example below:

Here, in this example python open json file and modify.

So let's see bellow example:

Example 1: Read JSON File in Python

So, in this example simple created data.json file:

data.json
[
  {
    "ID": 1,
    "Name": "Bhavesh Sonagra",
    "email": "[email protected]"
  },
  {
    "ID": 2,
    "Name": "Piyush Kamani",
    "email": "[email protected]"
  },
  {
    "ID": 3,
    "Name": "Nikhil Thumar",
    "email": "[email protected]"
  }
]
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": "Vishal Patel",
        "email": "[email protected]"
    })
  
# Append new object to list data
data.append({
        "ID": 5,
        "Name": "Divyesh Barad",
        "email": "[email protected]"
    })
    
# Create new JSON file
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)
  
# Closing file
f.close()
Output
[
  {
    "ID": 1,
    "Name": "Bhavesh Sonagra",
    "email": "[email protected]"
  },
  {
    "ID": 2,
    "Name": "Piyush Kamani",
    "email": "[email protected]"
  },
  {
    "ID": 3,
    "Name": "Nikhil Thumar",
    "email": "[email protected]"
  },
  {
    "ID": 4,
    "Name": "Vishal Patel",
    "email": "[email protected]"
  },
  {
    "ID": 5,
    "Name": "Divyesh Barad",
    "email": "[email protected]"
  }
]

It will help you....