Keep Your Best Scores in a JSON File

Everything a program keeps in its variables disappears when it stops. To remember something until the next run, such as the best score on each subject, the program has to write it into a file and read it back when it starts again. A file holds only text, so the data has to become text on the way out and turn back into data on the way in, and the program needs a plan for the very first run, when there is no file yet.

Writing a string to a file

A path, made with Path from the pathlib module, is the address of a file. You may already know its read_text method, which gives back the whole text of a file as one string. Its partner is write_text: it opens the file, writes the string you give it, and closes the file again.

from pathlib import Path

path = Path("message.txt")
path.write_text("See you tomorrow", encoding="utf-8")
print(path.read_text(encoding="utf-8"))  # See you tomorrow

Two things happen that are easy to miss. If message.txt does not exist, write_text creates it. If it already exists, everything it held is thrown away first and only the new string is left. Writing never adds to the end of a file; it always replaces the whole content. That is what you want for a file that holds the latest state of something, because each save leaves exactly one up-to-date copy.

Two writes to the same path
CallFile beforeFile after
write_text("See you tomorrow")does not existSee you tomorrow
write_text("Done")See you tomorrowDone

Naming the encoding with encoding="utf-8" decides how each letter is stored as bytes on the disk. Use the same encoding for writing and for reading, so a word like café comes back as it went in.

One more rule is strict: write_text accepts only a string. Handing it a dictionary stops the program with TypeError: data must be str, not dict, and a number fails the same way. So before a dictionary can be saved, it has to be turned into text. That is what JSON is for.

True or false?

Calling write_text twice on the same path leaves both strings in the file, one after the other.

False. Each call replaces what the file held. After the second call, only the second string is in the file.

write_text can write to a file that does not exist yet.

True. Opening a file for writing creates it when it is missing, as long as the folder it should sit in exists.

JSON: data written as plain text

A file holds text, but a dictionary lives in the memory of a running program. To store it, you need agreed rules for writing data as characters, so that the same characters can later be turned back into the same data. JSON (short for JavaScript Object Notation) is the most common set of such rules. It is plain text that people can read and edit, it does not belong to any one programming language, and files written in it usually end in .json.

JSON looks a lot like Python, which helps, but it is its own format with its own spelling. Here is one JSON document:

profile.json
{
  "name": "Ada",
  "scores": [3, 5, 4],
  "rate": 0.75,
  "finished": true,
  "note": null
}

The curly brackets hold an object, which works like a dictionary: names paired with values, a colon after each name and a comma between pairs. A name is always a string. The square brackets around 3, 5, 4 hold an array, which works like a list: an ordered row of values. The rest are simple values: strings, numbers and three fixed words, true, false and null. Each of these Python values has a JSON counterpart:

Python values and how JSON writes them
In PythonIn JSONExample in JSON
dictionaryobject{"python": 4}
listarray[3, 5, 4]
stringstring, in double quotes"Ada"
whole or decimal numbernumber4 or 0.75
True and Falsetrue and falsetrue
Nonenullnull

The differences are small and strict. Strings must use double quotes; 'Ada' with single quotes is not JSON. The three fixed words are written in small letters. JSON has no comments, and a comma after the last item, as in [3, 5,], is not allowed. A file that breaks one of these rules is not JSON, and a program reading it will refuse it.

True or false?

The text {'done': True} is valid JSON.

False. It breaks two rules: the name uses single quotes instead of double quotes, and JSON writes the value as true, in small letters.

In a JSON object, every name before a colon is a string.

True. JSON allows only strings as names, written in double quotes, even when the value after the colon is a number.

From Python data to JSON text and back

The json module of the standard library does the translation in both directions. json.dumps takes Python data and gives back a string of JSON text. json.loads takes a string of JSON text and gives back Python data. The s at the end of each name stands for string: neither function touches a file. Joined with write_text and read_text, they make a full trip from a dictionary to the disk and back.

  • dictionary in memory
  • JSON text a string
  • best.json on the disk
  • JSON text a string
  • dictionary next run
  • dictionary to JSON text: json.dumps
  • JSON text to best.json: write_text
  • best.json to JSON text: read_text
  • JSON text to dictionary: json.loads

Saving is the first half of that trip: turn the dictionary into text, then write the text.

Saving
import json
from pathlib import Path

best = {"python": 4, "history": 2}

text = json.dumps(best, indent=2)
Path("best.json").write_text(text, encoding="utf-8")

Without indent, json.dumps puts everything on one line: {"python": 4, "history": 2}. With indent=2, each pair goes on its own line, moved in by two spaces, which is easier to read when you open the file. Both are the same data.

best.json
{
  "python": 4,
  "history": 2
}

Loading is the second half: read the text, then turn it back into data. What comes back is an ordinary dictionary, so it is used like any other.

Loading
text = Path("best.json").read_text(encoding="utf-8")
best = json.loads(text)

print(best["python"] + 1)  # 5

The trip is not perfect for every kind of value, because JSON has fewer kinds than Python. Dictionary keys always come back as strings, since JSON names are strings: a dictionary with the key 1 loads back with the key "1". Keeping your keys as strings from the start avoids the surprise. The kinds of value in the table are the ones json.dumps can save: for any other kind it raises a TypeError.

True or false?

json.dumps writes a dictionary into a file.

False. json.dumps only returns a string of JSON text. Writing that string to a file is a separate step, for example with write_text.

After best = json.loads(text), best["python"] reads an entry exactly as with a dictionary written in the code.

True. A JSON object loads as an ordinary Python dictionary, so reading, changing and adding entries work as usual.

Saving {1: "one"} as JSON and loading it again gives back a dictionary with the key 1.

False. JSON names are always strings, so the key is saved as "1" and loads back as the string "1", not the number 1.

When the text is not valid JSON

json.loads checks the text against the rules of the format. If the text breaks one, it raises an exception called JSONDecodeError, and the program stops unless something handles it.

This happens when someone edits a file by hand and leaves a single quote or a trailing comma in it. It also happens when a file is empty. An empty string holds no value at all, so loading it ends the traceback with this line:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Read it like any traceback, from the bottom. JSONDecodeError is the type, printed with the name of the module it lives in. After the colon comes the message: what the reader expected, and the line and column where it gave up. That position points you to the exact character to fix in the file.

A file that does not exist at all raises a different type of exception, FileNotFoundError. Keep the two apart: an except that names one of them does not catch the other.

The first run, before the file exists

A program that loads its data at the start has a problem on the very first run: it has never saved anything, so the file is not there. read_text then raises FileNotFoundError, with a message such as [Errno 2] No such file or directory: 'best.json'. A missing file here is not a mistake. It only means there are no saved scores yet, so the right answer is to start with an empty dictionary.

  • Program starts
  • read_text best.json
  • FileNotFoundError start with {}
  • File found json.loads(text)
  • Program uses and changes the dictionary
  • write_text creates or replaces the file
  • Program starts to read_text
  • read_text to FileNotFoundError: first run
  • read_text to File found: later runs
  • FileNotFoundError to Program uses and changes the dictionary
  • File found to Program uses and changes the dictionary
  • Program uses and changes the dictionary to write_text creates or replaces the file

In code, try and except catch exactly that one expected error and give back an empty dictionary. Every later run finds the file, because the first save created it.

import json
from pathlib import Path


def load_best(path):
    try:
        text = path.read_text(encoding="utf-8")
    except FileNotFoundError:
        return {}
    return json.loads(text)


def save_best(path, best):
    path.write_text(json.dumps(best, indent=2), encoding="utf-8")


path = Path("best.json")
best = load_best(path)   # {} on the first run
best["python"] = 4
save_best(path, best)    # creates best.json

Only read_text sits inside the try, and the except names only FileNotFoundError. A file that exists but holds broken JSON still raises JSONDecodeError from json.loads, and the program stops with a message that points at the problem. Catching every error and quietly starting with an empty dictionary would hide that damage, and the next save would replace the old scores with the empty ones.

True or false?

An except FileNotFoundError around the loading code also handles a file that holds invalid JSON.

False. Invalid JSON raises JSONDecodeError, a different type of exception. An except that names FileNotFoundError lets it through.

On the second run of the program above, load_best finds the file and returns the saved dictionary.

True. The first run ended with save_best, which created best.json, so read_text succeeds and json.loads turns the text back into a dictionary.