Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 31 / 101

Trust the shape, not the filename.

Parse a configuration file and check what its values actually mean.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Parsing JSON proves that the text follows JSON syntax. It does not prove that the resulting object is valid for your application. A configuration contract should describe required keys, allowed types, and value ranges. Validate once at the boundary, then let the rest of the program rely on the validated result.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

json_contracts.py
import json
raw = '{"project": "Orbit", "retries": 3}'
config = json.loads(raw)
if not isinstance(config, dict):
    raise ValueError("Config must be an object")
if not isinstance(config.get("project"), str) or not config["project"].strip():
    raise ValueError("project must be nonempty text")
if type(config.get("retries")) is not int or not 0 <= config["retries"] <= 5:
    raise ValueError("retries must be an integer from 0 to 5")
print(config["project"], config["retries"])
↳ EXPECTED OUTPUT
Orbit 3

03 Under the hood

  1. 1

    json.loads turns the text into Python values. Start by checking the outer shape before indexing into it.

  2. 2

    The example uses type(value) is int because bool is a subclass of int in Python. True is not an appropriate retry count even though isinstance(True, int) is true.

  3. 3

    Error messages name the field and expected value. For larger systems, a schema library can standardise contracts, but you still need to define the intended semantics.

04 Your turn, builder

A SMALL MISSION

Validate that a decoded object has a positive integer timeout value.

Reveal one possible solution +
one_possible_solution.py
import json
config = json.loads('{"timeout": 15}')
value = config.get("timeout")
if type(value) is not int or value <= 0:
    raise ValueError("timeout must be a positive integer")
print(value)

05 Check your signal

QUICK SIGNAL CHECK

Does valid JSON guarantee the right application fields?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.