Module 20 · Building Real Python Applications — topic 9 of 13
JSON storage
Robust JSON persistence for applications: converting dataclasses and dates, a versioned file format with migrations, atomic saves, and recovering from corrupt files without losing data.
Learning objectives
- Convert application objects to and from JSON
- Version and migrate a file format
- Save atomically and recover from corrupt files
Definition
JSON storage keeps an application's data in a JSON file. A robust implementation converts custom types, records a format version, writes atomically and handles missing or corrupt files gracefully.
Introduction
JSON is the easiest way to store application data — until a date won't serialise, an old file has a different shape, or a crash leaves a half-written file. This lesson handles all three.
Why it matters
Users' data must survive upgrades and crashes. A few careful patterns make JSON storage dependable.
Detailed explanation
Convert objects to plain data before saving: dataclasses with asdict, dates with isoformat(), sets with sorted lists.
Convert back when loading: Expense(**item), date.fromisoformat(text).
Store a top-level object such as {"version": 2, "expenses": [...]} rather than a bare list, so metadata can be added later.
When the format changes, write a migrate function that upgrades old versions step by step, and save in the newest format.
Save atomically: write to a temporary file in the same folder, then os.replace it over the real file, so a crash never leaves a half-written file.
If the file is corrupt (JSONDecodeError), don't overwrite it: move it aside as a backup, tell the user, and start with empty data or the last good copy.
Use indent=2 for files people may inspect, and ensure_ascii=False for readable non-English text.
Keep all of this inside one storage class so the rest of the application only calls load() and save().
Syntax
- Convert objects to plain data.
- Version the format.
- Write atomically.
Code examples
Dates in JSON
[{"amount": 250, "category": "food", "date": "2026-11-27"}]
27 Nov 2026Migrating an old format
{'version': 2, 'expenses': [{'amount': 250, 'category': 'food'}, {'amount': 40, 'category': 'travel'}]}More examples
A robust expense file
[Expense(amount=250, category='food', note='lunch'), Expense(amount=40, category='travel', note='')] corrupt file moved to expenses.corrupt.json [] ['expenses.corrupt.json']
Step-by-step explanation
- save converts each dataclass with asdict and writes the versioned document atomically.
- load rebuilds Expense objects from the stored dictionaries.
- A corrupt file is moved aside instead of being overwritten, so its contents can still be recovered by hand.
Expected output
Running “A robust expense file” prints exactly:
Practical applications
- Desktop and command-line apps storing settings and documents.
- Games saving progress files.
Best practices
- Version your file format.
- Save atomically with os.replace.
- Back up corrupt files instead of overwriting them.
Common mistakes
Overwriting a corrupt file
Avoid
Prefer
The file may be recoverable; never destroy it automatically.
Important notes
- For multi-user or very large data, a database is a better fit than a JSON file.
Key takeaways
- Convert objects to plain JSON data and back.
- Version and migrate the format.
- Save atomically and recover from corruption safely.
Try it yourself
- 1Add a date field to Expense and store it as an ISO string.
- 2Keep the last three saves as rotating backups (expenses.1.json, ...).
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhy write data to a temporary file and then os.replace() it over the real file?