Write the Load Function
Exit

Write the Load Function

Create a function that reads expenses from the JSON file on startup

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Reading the file back

The save function writes data out. Now you need the reverse: a function that reads the JSON file and restores the expenses dictionary and counter.

json.loads() converts a JSON string back into a Python dictionary. Pair it with Path.read_text() to read the file contents:

data = json.loads(DATA_FILE.read_text())

The string key problem

JSON only supports string keys. When you save {1: {"id": 1, ...}}, JSON converts the integer key 1 to the string "1". On load, you get {"1": {"id": 1, ...}} instead of {1: {"id": 1, ...}}.

Your endpoints use integer identifiers to look up expenses. If the keys are strings after loading, every lookup fails. The fix is to convert keys back to integers with int(k) during the load.

Handling first run

The first time the server starts, no JSON file exists yet. Calling read_text() on a missing file raises a FileNotFoundError. Check DATA_FILE.exists() first and skip loading if the file is not there. The expenses dictionary and counter keep their default values.

Instructions

Create the load_expenses function right after save_expenses.

  1. Define a function named load_expenses that takes no arguments.
  2. Add global expenses, counter as the first line inside the function. This lets the function modify the module-level variables.
  3. Add an if DATA_FILE.exists(): check. Inside the if block, read and parse the file: data = json.loads(DATA_FILE.read_text()).
  4. Still inside the if block, restore the data: set expenses = {int(k): v for k, v in data["expenses"].items()} and set counter = data["counter"].