Python
json.load and dump
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.
Exercise 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"]).
Show example 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"])
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.
Test yourself
-
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
- Only a data parameter
Show answer
First the data, then the file — First data, then the file. Order matters.
-
Match the structured-data module
- json.load
- Reads from a file
- json.dump
- Writes to a file
- ensure_ascii
- Character setting
- indent
- Indentation setting
-
Complete the json.load call
with open("person.txt", encoding="utf-8") as f:
data = json.____(f)
print(data["name"])
Show answer
with open("person.txt", encoding="utf-8") as f:
data = json.load(f)
print(data["name"])
Next lesson: json.loads and dumps