Python todo notebook (2/6): read and write JSON
Load and save the todo notebook with json.load and json.dump, UTF-8, a readable indent, and an empty notebook when the file taches.json is missing.
Getting started
Home Assistant
Buying
Load and save the todo notebook with json.load and json.dump, UTF-8, a readable indent, and an empty notebook when the file taches.json is missing.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
The json module converts between JSON text and Python objects (dict, list, str, bool, int, float, None).
import json
from pathlib import Path
def charger(chemin: Path):
if not chemin.exists():
return {"prochain_id": 1, "taches": []}
with chemin.open("r", encoding="utf-8") as f:
return json.load(f)
If the file does not exist, return an empty structure that is ready to use.
def sauvegarder(chemin: Path, data):
with chemin.open("w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
ensure_ascii=False: keeps accented letters in the file instead of \u escapes.indent=2: readable JSON, with line breaks and indentation.json.JSONDecodeError. You can print a message and start again from an empty notebook (try/except).Path("taches.json") avoids mixing Windows and Unix slashes. chemin.exists() says clearly what you are testing. The pathlib lesson goes further if you want the whole module.
test.json by hand, load it and print type(data).json.load do? Wrap the call in try / except.Part 3 — Data model: add a task and increment the id.
A book search for Python, files and data: Check today’s price on Amazon.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).