Editor

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

read_write_json.py
import json
student = {
"name": "Riya",
"class": 12,
"subjects": ["Physics", "Chemistry", "Computer Science"],
"marks": {"Physics": 88, "Chemistry": 91, "Computer Science": 97},
}
# Write the dictionary to a file as JSON
with open("student.json", "w") as f:
json.dump(student, f, indent=2)
# Read it back: you get an ordinary dictionary again
with open("student.json", "r") as f:
data = json.load(f)
print("Name:", data["name"])
print("Subjects:", ", ".join(data["subjects"]))
print("Best mark:", max(data["marks"].values()))
# Add a value and save the file again
data["passed"] = True
with open("student.json", "w") as f:
json.dump(data, f, indent=2)
with open("student.json", "r") as f:
print("The file now contains:")
print(f.read())
Output
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

  1. json.dump(student, f, indent=2) writes the dictionary to the file as JSON text, and indent=2 spreads it over several lines so people can read it.
  2. json.load(f) reads the file and rebuilds the dictionary, with the list and the inner dictionary intact.
  3. After loading, data is a normal dictionary, so values are read with keys such as data["name"].
  4. To update a JSON file, load it, change the dictionary, and dump it again in "w" mode.
  5. JSON writes Python's True as true, False as false and None as null, and its keys are always strings.

Other ways to write it

Using dumps() and loads() with strings

Using dumps() and loads() with strings
import json
settings = {"theme": "dark", "font_size": 14, "autosave": True}
text = json.dumps(settings) # dictionary -> JSON string
print("As JSON text:", text)
print("Type:", type(text).__name__)
back = json.loads(text) # JSON string -> dictionary
print("Font size:", back["font_size"])
print("Type:", type(back).__name__)
Output
As JSON text: {"theme": "dark", "font_size": 14, "autosave": true}
Type: str
Font size: 14
Type: dict

The 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

A list of records
import json
# Make a sample file to work on
with open("contacts.json", "w") as f:
json.dump([{"name": "Aarav", "phone": "90000 11111"}], f)
with open("contacts.json", "r") as f:
contacts = json.load(f)
contacts.append({"name": "Diya", "phone": "90000 22222"})
with open("contacts.json", "w") as f:
json.dump(contacts, f, indent=2)
print("Saved", len(contacts), "contacts:")
for c in contacts:
print("-", c["name"], c["phone"])
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises