Skip to content

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.

Beginner 10 min read·Lesson 302 of 306 in Python Programming

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

Python
def save(path, expenses):
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps({"version": 2, "expenses": [asdict(e) for e in expenses]}, indent=2), encoding="utf-8")
os.replace(tmp, path)
  • Convert objects to plain data.
  • Version the format.
  • Write atomically.

Code examples

Dates in JSON

Python
import json
from datetime import date
expenses = [{"amount": 250, "category": "food", "date": date(2026, 11, 27)}]
text = json.dumps(expenses, default=lambda o: o.isoformat())
print(text)
loaded = json.loads(text)
for e in loaded:
e["date"] = date.fromisoformat(e["date"])
print(loaded[0]["date"].strftime("%d %b %Y"))
Output
[{"amount": 250, "category": "food", "date": "2026-11-27"}]
27 Nov 2026

Migrating an old format

Python
def migrate(data):
if data.get("version", 1) == 1:
data = {"version": 2, "expenses": [{"amount": a, "category": c} for a, c in data["items"]]}
return data
old = {"items": [[250, "food"], [40, "travel"]]}
print(migrate(old))
Output
{'version': 2, 'expenses': [{'amount': 250, 'category': 'food'}, {'amount': 40, 'category': 'travel'}]}

More examples

A robust expense file

Python
import json
import os
from dataclasses import asdict, dataclass
from pathlib import Path
@dataclass
class Expense:
amount: float
category: str
note: str = ""
class ExpenseFile:
def __init__(self, path):
self.path = Path(path)
def load(self):
if not self.path.exists():
return []
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
backup = self.path.with_suffix(".corrupt.json")
os.replace(self.path, backup)
print(f"corrupt file moved to {backup.name}")
return []
return [Expense(**item) for item in raw["expenses"]]
def save(self, expenses):
tmp = self.path.with_suffix(".tmp")
data = {"version": 2, "expenses": [asdict(e) for e in expenses]}
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
os.replace(tmp, self.path)
store = ExpenseFile("expenses.json")
store.save([Expense(250, "food", "lunch"), Expense(40, "travel")])
print(store.load())
Path("expenses.json").write_text("{oops", encoding="utf-8")
print(store.load(), sorted(p.name for p in Path(".").glob("expenses*")))
Output
[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:

TextOutput
[Expense(amount=250, category='food', note='lunch'), Expense(amount=40, category='travel', note='')]
corrupt file moved to expenses.corrupt.json
[] ['expenses.corrupt.json']

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

except json.JSONDecodeError:
save([]) # the user's data is gone

Prefer

except json.JSONDecodeError:
os.replace(path, backup)
return []

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

  1. 1
    Add a date field to Expense and store it as an ISO string.
  2. 2
    Keep 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?
Practise this topic