← Building with AI

Checking the data

Make sure the keys are there and the types are right.

Start this lesson

Parsed JSON can still be wrong: a key might be missing, an age might come back as the text 'thirty' instead of a number, or a value might be null. Before you save or use the data, check it. A handy pattern is a function that returns a list of problems. An empty list means the data is good, and a non-empty list tells you exactly what to fix.

def problems(data):
    found = []
    if not isinstance(data.get("title"), str):
        found.append("title should be text")
    if not isinstance(data.get("pages"), int):
        found.append("pages should be a whole number")
    return found

print(problems({"title": "Holes", "pages": 233}))      # []
print(problems({"title": "Holes", "pages": "many"}))   # ['pages should be a whole number']

data.get(key) returns None when the key is missing, so isinstance(None, str) is False and the problem is reported.

In Python, True and False count as ints (isinstance(True, int) is True). If a number must be a real number, also check that it is not a bool.

Also check ranges where it matters: an age of 500 is a number, but not a sensible one.

Bigger projects use libraries such as pydantic or jsonschema to do this checking. The idea is the same.