Type stubs for jsonschema JSON Schema validation library
Core validation functionality for validating JSON data against JSON Schema definitions. This module provides validator classes for different JSON Schema draft versions, validation functions, and reference resolution capabilities.
Main validation function that validates an instance against a JSON schema with automatic validator selection.
def validate(
instance: Any,
schema: dict,
cls: type | None = None,
*args,
**kwargs
) -> None:
"""
Validate an instance against a schema.
Args:
instance: The data to validate
schema: The JSON schema to validate against
cls: Validator class to use (auto-selected if None)
*args: Additional arguments for validator
**kwargs: Additional keyword arguments for validator
Raises:
ValidationError: If validation fails
SchemaError: If schema is invalid
"""Usage example:
from jsonschema import validate, ValidationError
schema = {"type": "string", "minLength": 5}
data = "hello"
try:
validate(data, schema)
print("Valid!")
except ValidationError as e:
print(f"Invalid: {e.message}")Get the appropriate validator class for a given schema.
def validator_for(schema: dict, default: type | None = None) -> type:
"""
Get the appropriate validator class for a schema.
Args:
schema: JSON schema
default: Default validator class if none found
Returns:
Validator class appropriate for the schema
"""Validator for JSON Schema Draft 3 specification.
class Draft3Validator:
"""JSON Schema Draft 3 validator."""
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
def check_schema(self, schema: dict) -> None:
"""Check if a schema is valid."""
def is_type(self, instance: Any, type: str) -> bool:
"""Check if instance is of the given type."""
def is_valid(self, instance: Any) -> bool:
"""Check if instance is valid against the schema."""
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
"""Iterate over validation errors for an instance."""
def validate(self, instance: Any) -> None:
"""Validate an instance, raising ValidationError on failure."""
def evolve(self, **kwargs) -> Draft3Validator:
"""Create a new validator with modified parameters."""Validator for JSON Schema Draft 4 specification.
class Draft4Validator:
"""JSON Schema Draft 4 validator."""
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
def check_schema(self, schema: dict) -> None:
"""Check if a schema is valid."""
def is_type(self, instance: Any, type: str) -> bool:
"""Check if instance is of the given type."""
def is_valid(self, instance: Any) -> bool:
"""Check if instance is valid against the schema."""
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
"""Iterate over validation errors for an instance."""
def validate(self, instance: Any) -> None:
"""Validate an instance, raising ValidationError on failure."""
def evolve(self, **kwargs) -> Draft4Validator:
"""Create a new validator with modified parameters."""Validator for JSON Schema Draft 6 specification.
class Draft6Validator:
"""JSON Schema Draft 6 validator."""
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
def check_schema(self, schema: dict) -> None:
"""Check if a schema is valid."""
def is_type(self, instance: Any, type: str) -> bool:
"""Check if instance is of the given type."""
def is_valid(self, instance: Any) -> bool:
"""Check if instance is valid against the schema."""
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
"""Iterate over validation errors for an instance."""
def validate(self, instance: Any) -> None:
"""Validate an instance, raising ValidationError on failure."""
def evolve(self, **kwargs) -> Draft6Validator:
"""Create a new validator with modified parameters."""Validator for JSON Schema Draft 7 specification (most commonly used).
class Draft7Validator:
"""JSON Schema Draft 7 validator."""
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
def check_schema(self, schema: dict) -> None:
"""Check if a schema is valid."""
def is_type(self, instance: Any, type: str) -> bool:
"""Check if instance is of the given type."""
def is_valid(self, instance: Any) -> bool:
"""Check if instance is valid against the schema."""
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
"""Iterate over validation errors for an instance."""
def validate(self, instance: Any) -> None:
"""Validate an instance, raising ValidationError on failure."""
def evolve(self, **kwargs) -> Draft7Validator:
"""Create a new validator with modified parameters."""Usage example:
from jsonschema import Draft7Validator
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
validator = Draft7Validator(schema)
# Check if data is valid
data = {"name": "Alice", "age": 25}
if validator.is_valid(data):
print("Valid!")
# Get all validation errors
invalid_data = {"age": -5}
for error in validator.iter_errors(invalid_data):
print(f"Error at {'.'.join(str(p) for p in error.path)}: {error.message}")System for resolving JSON Schema references ($ref) to enable schema composition and reuse.
class RefResolver:
"""Resolver for JSON Schema references."""
referrer: dict
cache_remote: bool
handlers: dict
store: dict
def __init__(
self,
base_uri: str,
referrer: dict,
store: dict | None = None,
cache_remote: bool = True,
handlers: dict | None = None,
urljoin_cache: dict | None = None,
remote_cache: dict | None = None
) -> None:
"""
Initialize reference resolver.
Args:
base_uri: Base URI for resolving relative references
referrer: Schema being resolved
store: Pre-loaded schema store
cache_remote: Whether to cache remote schemas
handlers: Custom URI handlers
urljoin_cache: Cache for URI joining operations
remote_cache: Cache for remote schema retrieval
"""
@classmethod
def from_schema(cls, schema: dict, id_of: Callable = None, *args, **kwargs) -> RefResolver:
"""Create resolver from a schema."""
def push_scope(self, scope: str) -> None:
"""Push a new resolution scope."""
def pop_scope(self) -> None:
"""Pop the current resolution scope."""
@property
def resolution_scope(self) -> str:
"""Current resolution scope."""
@property
def base_uri(self) -> str:
"""Base URI for resolution."""
def in_scope(self, scope: str) -> ContextManager[None]:
"""Context manager for temporary scope changes."""
def resolving(self, ref: str) -> ContextManager[tuple]:
"""Context manager for resolving a reference."""
def resolve(self, ref: str) -> tuple:
"""
Resolve a reference.
Args:
ref: Reference to resolve
Returns:
(resolved_url, resolved_schema) tuple
"""
def resolve_from_url(self, url: str) -> tuple:
"""Resolve from a URL."""
def resolve_fragment(self, document: dict, fragment: str) -> Any:
"""Resolve a fragment within a document."""
def resolve_remote(self, uri: str) -> dict:
"""Resolve a remote schema."""Usage example:
from jsonschema import RefResolver, Draft7Validator
# Schema with references
main_schema = {
"type": "object",
"properties": {
"person": {"$ref": "#/definitions/person"}
},
"definitions": {
"person": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
}
}
}
}
resolver = RefResolver.from_schema(main_schema)
validator = Draft7Validator(main_schema, resolver=resolver)
data = {"person": {"name": "Bob", "age": 30}}
validator.validate(data) # Will resolve the $ref automaticallyCreate custom validator classes with specific validation rules.
def create(
meta_schema: dict,
validators: dict | None = None,
version: str | None = None,
default_types: dict | None = None,
type_checker: TypeChecker | None = None,
id_of: Callable | None = None
) -> type:
"""
Create a custom validator class.
Args:
meta_schema: Meta-schema for the validator
validators: Custom validation functions
version: Version identifier
default_types: Default type definitions
type_checker: Type checker instance
id_of: Function to extract schema ID
Returns:
New validator class
"""
def extend(
validator: type,
validators: dict | None = None,
version: str | None = None,
type_checker: TypeChecker | None = None
) -> type:
"""
Extend an existing validator class.
Args:
validator: Base validator class to extend
validators: Additional validation functions
version: Version identifier
type_checker: Type checker instance
Returns:
Extended validator class
"""
def validates(version: str) -> Callable:
"""
Decorator for registering validation functions.
Args:
version: JSON Schema version
Returns:
Decorator function
"""Access to validator registry and meta-schemas for different JSON Schema drafts.
# Dictionary of available validators by draft version
validators: dict[str, type]
# Dictionary of meta-schemas for each JSON Schema draft
meta_schemas: dict[str, dict]Usage example:
from jsonschema.validators import validators, meta_schemas
# Access available validators
draft7_validator_class = validators.get('draft7')
# Access meta-schemas
draft7_meta_schema = meta_schemas.get('draft7')
print(f"Meta-schema title: {draft7_meta_schema.get('title', 'Unknown')}")from typing import Any, Callable, ContextManager, Iterator, dict
from jsonschema.exceptions import ValidationError
from jsonschema._format import FormatChecker
from jsonschema._types import TypeCheckerInstall with Tessl CLI
npx tessl i tessl/pypi-types-jsonschema