Intermediate 8 min

Files and JSON

A file preserves data between program runs, and JSON gives lists and objects a portable text format.

How it works

Separate loading the data from using it. Decoding can succeed even when a field you expect is absent or has the wrong type. After loading a list of reading records, check the fields each record needs before processing them. File, JSON, and data shape errors call for different fixes.

Walk through an example

Open a text file with with open(path, encoding="utf-8") as file, then pass the file to json.load(file). A JSON array becomes a Python list.

What to watch for

Reading can fail because a file is missing or because its text is malformed. Handle those cases separately when each needs a different message.

Code example

import json
record = json.loads('{"done": true, "count": 2}')
print(record["done"])

Check your understanding

After decoding, what is the Python value of done?

See the example and explanation
Worked example
Given {"done": true, "count": 2}
Answer True

The JSON boolean literal true becomes Python’s boolean value True.

Open practice problem
Next lessonClasses, instances, and dataclasses