09-Jan-2023
.
Admin
Hi Dev,
In this article we will cover on how to implement modify json file in python tutorial example. In this article, we will implement a python json update value by key. This article goes in detailed on how to edit a json file python. This tutorial will give you simple example of python open json file and edit.
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:
Example :
main.py
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": "Piyush Patel",
"email": "piyush@gmail.com"
},
{
"ID": 2,
"Name": "Savan Rathod",
"email": "savan@gmail.com"
},
{
"ID": 3,
"Name": "Raju Mochi",
"email": "raju@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": "Rahul Shinde",
"email": "rahul@gmail.com"
})
# Append new object to list data
data.append({
"ID": 5,
"Name": "Jaydip Pathar",
"email": "jaydip@gmail.com"
})
# 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": "Piyush Patel",
"email": "piyush@gmail.com"
},
{
"ID": 2,
"Name": "Savan Rathod",
"email": "savan@gmail.com"
},
{
"ID": 3,
"Name": "Raju Mochi",
"email": "raju@gmail.com"
},
{
"ID": 4,
"Name": "Rahul Shinde",
"email": "rahul@gmail.com"
},
{
"ID": 5,
"Name": "Jaydip Pathar",
"email": "jaydip@gmail.com"
}
]
#Python