How to Modify JSON File in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Create JSON File from Dict Example
- Python Create JSON File from List Example
- How to Write a JSON File in Python?
- How to Read a JSON File in Python?
- How to Create a JSON File in Python?
- Python Read CSV File Without Header Example
- How to Read a CSV File in Python?
- Python Read Text File into List Example
- How to Read Text File Line by Line in Python?
- Python Create Text File in Specific Directory Example
- Python List Add Element at Beginning Example
- Python Create Zip Archive from Directory Example