Python Program to Read and Write a JSON File
Intermediate · File handling
JSON (JavaScript Object Notation) is a text format for structured data, and it is how most websites and apps exchange data. Python's json module turns dictionaries and lists into JSON text and back again. This program saves a student's details to a JSON file, reads them back, adds a value and saves the file again.
Program
Name: Riya
Subjects: Physics, Chemistry, Computer Science
Best mark: 97
The file now contains:
{
"name": "Riya",
"class": 12,
"subjects": [
"Physics",
"Chemistry",
"Computer Science"
],
"marks": {
"Physics": 88,
"Chemistry": 91,
"Computer Science": 97
},
"passed": true
}How it works
json.dump(student, f, indent=2)writes the dictionary to the file as JSON text, andindent=2spreads it over several lines so people can read it.json.load(f)reads the file and rebuilds the dictionary, with the list and the inner dictionary intact.- After loading,
datais a normal dictionary, so values are read with keys such asdata["name"]. - To update a JSON file, load it, change the dictionary, and dump it again in "w" mode.
- JSON writes Python's
Trueastrue,FalseasfalseandNoneasnull, and its keys are always strings.
Other ways to write it
Using dumps() and loads() with strings
As JSON text: {"theme": "dark", "font_size": 14, "autosave": true}
Type: str
Font size: 14
Type: dictThe s in dumps() and loads() stands for string: they convert to and from text in memory, which is what you use for JSON that arrives from a website instead of a file.
A list of records
Saved 2 contacts: - Aarav 90000 11111 - Diya 90000 22222
A JSON file can hold a list of dictionaries, which works like a tiny database: load the list, add a record, and write the whole list back.
Try it yourself
Add a "city" key to student before saving it, and print it after loading the file.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Read a CSV File
- Write a CSV File
- Work with a Nested Dictionary
- Update Marks in a Binary File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises