Working with text and files
Read and write JSON
Save lists and dictionaries as JSON and load them back with the json module.
Lesson 32 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
JSON can represent objects, arrays, strings, numbers, true or false, and null. Python’s json module converts between JSON text and matching Python values. Use dumps() to create JSON text and loads() to parse it.
For file practice, download the Python practice files v1.0.0 bundle. The examples write their own files, so the samples stay unchanged. Work on a copy if you edit a sample.
import json
settings = {"subject": "Python", "minutes": 25}
encoded = json.dumps(settings)
restored = json.loads(encoded)
print(restored["subject"])
print(restored["minutes"] + 5)Python 30
Save JSON to a file
Write UTF-8 JSON with pathlib, then load it back. json.dumps(..., indent=2) makes the saved file easier to read. Writing replaces an existing file at that path.
import json
from pathlib import Path
path = Path("my_settings.json")
path.write_text(json.dumps({"goal": 3}, indent=2), encoding="utf-8")
loaded = json.loads(path.read_text(encoding="utf-8"))
print(loaded["goal"])3
Why this works
json.dumps() converts Python values to JSON text, and json.loads() converts JSON text back to Python values. A JSON object usually becomes a Python dictionary and a JSON array becomes a list. Loading a numeric JSON value gives a number, unlike the text fields returned by csv.reader.
Practice
Save a dictionary with your subject and planned sessions to a JSON file. Read it back and print the values. Use a practice filename so you do not replace an important file. Then load the sample settings.json from the practice bundle and print its minutes plus 5; you should see 30.
Does json.loads() parse JSON text or write a file?
Reveal answer
It parses JSON text into Python values.
Try another case
After loading {"goal": 3} from JSON, can you add 2 to the goal without int()?
Check your answer
Reveal answer
Yes. JSON numeric values load as Python numbers, so the goal is an int in this example.
Your progress
Reveal the check answer or reach the end to complete this lesson.