An implementation of JSON Schema validation for Python
npx @tessl/cli install tessl/pypi-jsonschema@4.25.0A comprehensive implementation of the JSON Schema specification for Python, providing validation of JSON data against schemas with full support for multiple JSON Schema draft versions. jsonschema enables validation of JSON data, API input validation, configuration file validation, and any application requiring structured data validation against predefined schemas.
pip install jsonschemapip install jsonschema[format] for format validationimport jsonschemaCommon imports for validation:
from jsonschema import validate, ValidationError, Draft202012ValidatorFor format validation:
from jsonschema import FormatCheckerfrom jsonschema import validate, ValidationError
# Define a schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"]
}
# Valid data
data = {"name": "John Doe", "age": 30, "email": "john@example.com"}
try:
validate(instance=data, schema=schema)
print("Data is valid!")
except ValidationError as e:
print(f"Validation failed: {e.message}")
# Using a specific validator class
from jsonschema import Draft202012Validator
validator = Draft202012Validator(schema)
if validator.is_valid(data):
print("Valid!")
else:
for error in validator.iter_errors(data):
print(f"Error: {error.message}")jsonschema is built around a modular architecture with key components:
This design enables precise JSON Schema compliance, extensive customization capabilities, and integration with various Python frameworks and applications.
Essential validation functionality including the main validate function, validator creation, and schema compliance checking.
def validate(instance, schema, cls=None, *args, **kwargs): ...
def validator_for(schema, default=_UNSET): ...Draft-specific validator implementations providing full compliance with each JSON Schema specification version, from Draft 3 through Draft 2020-12.
class Draft202012Validator:
def __init__(self, schema, registry=None, resolver=None, format_checker=None): ...
def validate(self, instance): ...
def is_valid(self, instance): ...
def iter_errors(self, instance): ...
class Draft201909Validator: ...
class Draft7Validator: ...
class Draft6Validator: ...
class Draft4Validator: ...
class Draft3Validator: ...Comprehensive error reporting with detailed validation failure information, error trees for complex validation scenarios, and utilities for finding the most relevant errors.
class ValidationError(Exception):
def __init__(self, message, validator=None, path=(), context=(), ...): ...
@property
def message: str
@property
def path: deque
@property
def schema_path: deque
class SchemaError(Exception): ...
class ErrorTree: ...
def best_match(errors, key=None): ...Extensible format checking system supporting built-in formats like email, URI, date-time, and custom format validators.
class FormatChecker:
def __init__(self, formats=None): ...
def check(self, instance, format): ...
def checks(self, format, raises=()): ...
# Built-in format checkers
draft202012_format_checker: FormatChecker
draft201909_format_checker: FormatChecker
draft7_format_checker: FormatChecker
draft6_format_checker: FormatChecker
draft4_format_checker: FormatChecker
draft3_format_checker: FormatCheckerCustomizable type checking system for JSON Schema types with built-in type checkers for each draft version and extensibility for custom type definitions.
class TypeChecker:
def __init__(self, type_checkers=()): ...
def is_type(self, instance, type): ...
def redefine(self, type, fn): ...
def redefine_many(self, definitions=()): ...
def remove(self, *types): ...
# Built-in type checkers
draft202012_type_checker: TypeChecker
draft201909_type_checker: TypeChecker
draft7_type_checker: TypeChecker
draft6_type_checker: TypeChecker
draft4_type_checker: TypeChecker
draft3_type_checker: TypeCheckerAdvanced validator creation and extension capabilities for building custom validators, extending existing ones, and registering new schema versions.
def create(meta_schema, validators=(), version=None, type_checker=None, format_checker=None, id_of=None, applicable_validators=None): ...
def extend(validator, validators=(), version=None, type_checker=None, format_checker=None): ...
def validates(version): ...from typing import Any, Iterable, Mapping, Callable
from collections.abc import Sequence
from collections import deque
# Schema types
Schema = Mapping[str, Any] | bool
# Validation function signature
SchemaKeywordValidator = Callable[[Validator, Any, Any, Schema], Iterable[ValidationError]]
# Path types
PathType = deque[str | int]class UndefinedTypeCheck(Exception):
"""Raised when an undefined type is used in type checking."""
class UnknownType(Exception):
"""Raised when an unknown type is encountered."""
class FormatError(Exception):
"""Raised when format validation fails."""