jsonschema

4.26.0 · active · verified Sat Mar 28

jsonschema is the most complete and spec-compliant JSON Schema validator for Python, supporting Draft 3, 4, 6, 7, 2019-09, and 2020-12. The current stable release is 4.26.0 (requires Python ≥ 3.10). Releases follow semantic versioning and ship frequently via GitHub; minor releases are expected to be backwards-compatible while major versions may carry deprecations that become removals.

Warnings

Install

Imports

Quickstart

Validate a dict against a JSON Schema, collect all errors with a versioned validator, and demonstrate format checking.

from jsonschema import Draft202012Validator, FormatChecker, ValidationError

schema = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "price": {"type": "number", "minimum": 0},
        "email": {"type": "string", "format": "email"},
    },
    "required": ["name", "price"],
}

# Reuse the validator object for efficiency (avoid re-creating per call)
# Pass format_checker to activate 'format' keyword assertions;
# without it, 'format' is purely informational and never raises.
validator = Draft202012Validator(schema, format_checker=FormatChecker())

good = {"name": "Widget", "price": 9.99, "email": "user@example.com"}
bad  = {"name": "Widget", "price": "free", "email": "not-an-email"}

# validate() raises on the FIRST error; use iter_errors() for all errors.
try:
    validator.validate(good)
    print("good instance: valid")
except ValidationError as exc:
    print(f"Unexpected error: {exc.message}")

all_errors = list(validator.iter_errors(bad))
for err in all_errors:
    # err.path holds the JSON path to the failing field
    field = " -> ".join(str(p) for p in err.absolute_path) or "<root>"
    print(f"[{field}] {err.message}")

# Schema validity check (raises SchemaError if the schema is malformed)
Draft202012Validator.check_schema(schema)

view raw JSON →