Intermediate level · Module 1: Files and Structured Data in Python · Lesson 3 of 3
Saving and Loading JSON
Use JSON to save program data between runs and to exchange data with web services.
In this lesson you will
- Convert Python dictionaries and lists to JSON and back
- Choose between CSV and JSON for a task
Key concepts
serialisationjson.dump/json.loadnested dataindentation for readability
The lesson
JSON is a text format for structured data — lists and dictionaries — used by almost every web API and many apps. Python's json module converts between JSON text and Python objects.
json.dump(data, f, indent=2, ensure_ascii=False) saves a Python object to a file in readable form; json.load(f) reads it back. Unlike CSV, JSON can store nested structures such as a product with a list of sizes.
When your program starts, load the saved data if the file exists; otherwise start with defaults. Save after every change so nothing is lost if the computer loses power — common where electricity is unreliable.
Step by step
- Represent your products as a list of dictionaries.
- Save them to products.json with indent=2.
- On start-up, load the file if it exists, otherwise use defaults.
- Change a price, save, restart and confirm the change persisted.
Practice activity
Make your Beginner-level shop program save its products and prices to products.json and load them at startup.
Expected result: Program data survives a restart because it is saved to and loaded from JSON.
Check your understanding
-
When is JSON a better choice than CSV?
Show answer
When the data is nested or hierarchical, or when exchanging data with web APIs.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.