Programming paths / Python

Python learning path

Use Python for automation, data work, AI applications, and APIs while learning typing, validation, and testing.

Starter lesson

Validate structured input before using it

JSON decoding converts text into Python objects, but it does not guarantee that required fields have the expected types. Validate that boundary explicitly.

import json

def enabled_user_id(raw: str) -> int | None:
    record = json.loads(raw)
    user_id = record.get("user_id")

    if record.get("enabled") is True and isinstance(user_id, int):
        return user_id
    return None

print(enabled_user_id('{"user_id": 24, "enabled": true}'))

What to expect

24

Key idea: Parsing answers “is this valid JSON?”; application validation answers “is this the data my program needs?”

← Browse all programming paths