json.load and dump
- Python course
- Intermediate
- Lesson 73/116
- 5 min
Learn to read and write JSON with json.load and dump.
Structured data format on disk
The structured data format stores dicts and lists as plain text. Python's structured-data module reads and writes this format. You import it with import json.
To read from a file use json.load(f); the returned value is a Python dict or list. To write to a file use json.dump(data, f, ensure_ascii=False, indent=2). ensure_ascii=False keeps Turkish characters as they are; indent=2 gives readable indentation.
Practice Write data to a file and read it back
Start with import json. Define a dict with data = {"name": "Ayşe", "age": 30}. In a with open("person.txt", "w", encoding="utf-8") as f: block write json.dump(data, f, ensure_ascii=False, indent=2). Then in a with open("person.txt", "r", encoding="utf-8") as f: block do loaded = json.load(f). Print the name with print(loaded["name"]).
Starter code
import json
# Define a data dict
# Write it to a file, read back and print the nameSample solution
import json
# Define a data dict
data = {"name": "Ayşe", "age": 30}
# Write it to a file, read back and print the name
with open("person.txt", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open("person.txt", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"])Expected output
Ayşe
ensure_ascii and indent
By default json.dump turns Turkish characters into escape sequences like \u00e7. With ensure_ascii=False the letters are written as is; the file becomes human-readable. For Turkish content this parameter is almost always used.
The indent=2 parameter adds two-space indentation to the output. This lets you see the structure when opening the file in a text editor. For a compact file you omit indent; it writes a single line.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What parameter order does json.dump use to write?
- First the file, then the data
- Only a file parameter
- First the data, then the file Correct answer
- Only a data parameter
Explanation: First data, then the file. Order matters.
2 Match the structured-data module
| Term | Meaning |
|---|---|
json.load |
Reads from a file |
json.dump |
Writes to a file |
ensure_ascii |
Character setting |
indent |
Indentation setting |
3 Complete the json.load call
with open("person.txt", encoding="utf-8") as f:
data = json.____(f)
print(data["name"])
with open("person.txt", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])
Explanation: json.load(f) reads structured data from a file.