Validate JSON data with schemas, types, required fields, formats, composition, and API contracts.
Lessons
Validate JSON with the jsonschema library.
Validating in Python is easiest to learn by reading the example, changing it, and observing the result.
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"required": ["slug", "title"],
"properties": {
"slug": {"type": "string"},
"title": {"type": "string", "minLength": 3},
},
}
try:
validate(instance={"slug": "json", "title": "JSON Schema"}, schema=schema)
print("valid")
except ValidationError as error:
print("invalid:", error.message)Practice the Validating in Python example in a small scratch file, then explain what changed and why.