Type stubs for jsonschema JSON Schema validation library
Comprehensive exception hierarchy and error reporting system for JSON Schema validation. This module provides detailed validation failure information, error organization, and utilities for error analysis.
Internal base class for jsonschema errors. Both ValidationError and SchemaError inherit from this class.
class _Error(Exception):
"""Base class for jsonschema validation and schema errors."""
message: Any
path: Any
schema_path: Any
context: Any
cause: Any
validator: Any
validator_value: Any
instance: Any
schema: Any
parent: Any
def __init__(
self,
message: str,
validator: str | None = None,
path: Sequence[str | int] | None = None,
cause: Exception | None = None,
context: list[ValidationError] | None = None,
validator_value: Any = None,
instance: Any = None,
schema: dict | None = None,
schema_path: Sequence[str] | None = None,
parent: ValidationError | None = None
) -> None: ...
def __unicode__(self) -> str:
"""Return unicode representation of the error."""
@classmethod
def create_from(cls, other: _Error) -> _Error:
"""Create a new error from another error."""
@property
def absolute_path(self) -> Sequence[str | int]:
"""Absolute path to the failing instance."""
@property
def absolute_schema_path(self) -> Sequence[str]:
"""Absolute path to the failing schema keyword."""Main exception raised when JSON Schema validation fails. Inherits from _Error.
class ValidationError(_Error):
"""Exception raised when JSON Schema validation fails."""
message: str
path: Sequence[str | int]
schema_path: Sequence[str]
context: list[ValidationError]
cause: Exception | None
validator: str
validator_value: Any
instance: Any
schema: dict
parent: ValidationError | None
def __init__(
self,
message: str,
validator: str | None = None,
path: Sequence[str | int] | None = None,
cause: Exception | None = None,
context: list[ValidationError] | None = None,
validator_value: Any = None,
instance: Any = None,
schema: dict | None = None,
schema_path: Sequence[str] | None = None,
parent: ValidationError | None = None
) -> None:
"""
Initialize validation error.
Args:
message: Human-readable error message
validator: Name of the failing validator
path: Path to the failing instance
cause: Underlying exception that caused this error
context: List of sub-errors
validator_value: Value of the failing validator in schema
instance: The failing instance value
schema: Schema that failed validation
schema_path: Path to the failing schema keyword
parent: Parent error in error hierarchy
"""
@classmethod
def create_from(cls, other: ValidationError) -> ValidationError:
"""Create a new ValidationError from another error."""
@property
def absolute_path(self) -> Sequence[str | int]:
"""Absolute path to the failing instance."""
@property
def absolute_schema_path(self) -> Sequence[str]:
"""Absolute path to the failing schema keyword."""Usage example:
from jsonschema import Draft7Validator, ValidationError
schema = {
"type": "object",
"properties": {
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
validator = Draft7Validator(schema)
data = {"age": -5}
try:
validator.validate(data)
except ValidationError as e:
print(f"Message: {e.message}")
print(f"Path: {'.'.join(str(p) for p in e.path)}")
print(f"Schema path: {'.'.join(e.schema_path)}")
print(f"Validator: {e.validator}")
print(f"Failed value: {e.instance}")Exception raised when a JSON schema itself is invalid.
class SchemaError(_Error):
"""Exception raised when a schema is invalid."""
message: str
path: Sequence[str | int]
schema_path: Sequence[str]
context: list[ValidationError]
cause: Exception | None
validator: str
validator_value: Any
instance: Any
schema: dict
parent: ValidationError | None
def __init__(
self,
message: str,
validator: str | None = None,
path: Sequence[str | int] | None = None,
cause: Exception | None = None,
context: list[ValidationError] | None = None,
validator_value: Any = None,
instance: Any = None,
schema: dict | None = None,
schema_path: Sequence[str] | None = None,
parent: ValidationError | None = None
) -> None: ...
@classmethod
def create_from(cls, other: ValidationError) -> SchemaError: ...
@property
def absolute_path(self) -> Sequence[str | int]: ...
@property
def absolute_schema_path(self) -> Sequence[str]: ...Usage example:
from jsonschema import Draft7Validator, SchemaError
# Invalid schema - type should be a string, not a list
invalid_schema = {
"type": ["string", "number", "invalid"] # "invalid" is not a valid type
}
try:
validator = Draft7Validator(invalid_schema)
validator.check_schema(invalid_schema)
except SchemaError as e:
print(f"Schema error: {e.message}")
print(f"Schema path: {'.'.join(e.schema_path)}")Exception raised when JSON Schema reference ($ref) resolution fails.
class RefResolutionError(Exception):
"""Exception raised when a $ref cannot be resolved."""
def __init__(self, cause: Exception) -> None:
"""
Initialize reference resolution error.
Args:
cause: Underlying exception that caused resolution failure
"""
def __lt__(self, other: RefResolutionError) -> bool:
"""Less than comparison for RefResolutionError instances."""
def __le__(self, other: RefResolutionError) -> bool:
"""Less than or equal comparison for RefResolutionError instances."""
def __gt__(self, other: RefResolutionError) -> bool:
"""Greater than comparison for RefResolutionError instances."""
def __ge__(self, other: RefResolutionError) -> bool:
"""Greater than or equal comparison for RefResolutionError instances."""Usage example:
from jsonschema import Draft7Validator, RefResolver, RefResolutionError
schema = {
"type": "object",
"properties": {
"person": {"$ref": "#/definitions/nonexistent"} # Invalid reference
}
}
try:
resolver = RefResolver.from_schema(schema)
validator = Draft7Validator(schema, resolver=resolver)
validator.validate({"person": {"name": "Alice"}})
except RefResolutionError as e:
print(f"Reference resolution failed: {e}")Exception raised when string format validation fails.
class FormatError(Exception):
"""Exception raised when format validation fails."""
message: str
cause: Exception | None
def __init__(self, message: str, cause: Exception | None = None) -> None:
"""
Initialize format error.
Args:
message: Error message
cause: Underlying exception
"""
def __unicode__(self) -> str:
"""Return unicode representation of the format error."""Exceptions related to type validation system.
class UndefinedTypeCheck(Exception):
"""Exception raised when a type check is undefined."""
type: str
def __init__(self, type: str) -> None:
"""
Initialize undefined type check error.
Args:
type: The undefined type name
"""
def __unicode__(self) -> str:
"""Return unicode representation of the error."""
class UnknownType(Exception):
"""Exception raised when an unknown type is encountered."""
type: str
instance: Any
schema: dict
def __init__(self, type: str, instance: Any, schema: dict) -> None:
"""
Initialize unknown type error.
Args:
type: The unknown type name
instance: The instance being validated
schema: The schema containing the unknown type
"""
def __unicode__(self) -> str:
"""Return unicode representation of the error."""Tree structure for organizing and navigating validation errors hierarchically.
class ErrorTree:
"""Tree structure for organizing validation errors."""
errors: dict
def __init__(self, errors: Iterable[ValidationError] | None = None) -> None:
"""
Initialize error tree.
Args:
errors: Iterable of validation errors to organize
"""
def __contains__(self, index: str | int) -> bool:
"""Check if error exists at given index."""
def __getitem__(self, index: str | int) -> ErrorTree:
"""Get error subtree at given index."""
def __setitem__(self, index: str | int, value: ErrorTree) -> None:
"""Set error subtree at given index."""
def __iter__(self) -> Iterator[ValidationError]:
"""Iterate over errors in tree."""
def __len__(self) -> int:
"""Get number of direct errors in tree."""
@property
def total_errors(self) -> int:
"""Get total number of errors including subtrees."""Usage example:
from jsonschema import Draft7Validator, ErrorTree
schema = {
"type": "object",
"properties": {
"users": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name", "age"]
}
}
}
}
validator = Draft7Validator(schema)
data = {
"users": [
{"name": "Alice"}, # Missing age
{"name": "Bob", "age": -5}, # Invalid age
{"age": 25} # Missing name
]
}
errors = validator.iter_errors(data)
tree = ErrorTree(errors)
# Navigate errors by path
if "users" in tree:
users_errors = tree["users"]
if 0 in users_errors: # First user errors
print(f"First user has {len(users_errors[0])} errors")
if 1 in users_errors: # Second user errors
print(f"Second user has {len(users_errors[1])} errors")
print(f"Total errors: {tree.total_errors}")Utilities for analyzing and selecting the most relevant validation errors.
def by_relevance(
weak: Callable[[ValidationError], float] = None,
strong: Callable[[ValidationError], float] = None
) -> Callable[[ValidationError], float]:
"""
Create error relevance function.
Args:
weak: Function to compute weak relevance score
strong: Function to compute strong relevance score
Returns:
Relevance scoring function
"""
def best_match(
errors: Iterable[ValidationError],
key: Callable[[ValidationError], float] = None
) -> ValidationError:
"""
Find the most relevant error from a collection.
Args:
errors: Collection of validation errors
key: Function to compute error relevance score
Returns:
Most relevant validation error
"""
# Default relevance function
relevance: Callable[[ValidationError], float]
# Constants for relevance scoring
WEAK_MATCHES: dict
STRONG_MATCHES: dictUsage example:
from jsonschema import Draft7Validator, best_match
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0, "maximum": 150}
},
"required": ["name", "age"]
}
validator = Draft7Validator(schema)
data = {"name": 123, "age": -5} # Multiple errors
errors = list(validator.iter_errors(data))
most_relevant = best_match(errors)
print(f"Most relevant error: {most_relevant.message}")
print(f"At path: {'.'.join(str(p) for p in most_relevant.path)}")from jsonschema import Draft7Validator, ValidationError, ErrorTree, best_match
schema = {
"type": "object",
"properties": {
"profile": {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 0, "maximum": 150}
},
"required": ["name", "email"]
}
},
"required": ["profile"]
}
validator = Draft7Validator(schema)
data = {
"profile": {
"name": "",
"email": "invalid-email",
"age": -5
}
}
try:
validator.validate(data)
except ValidationError as e:
# Get all errors
all_errors = list(validator.iter_errors(data))
# Organize in tree structure
error_tree = ErrorTree(all_errors)
# Find most relevant error
primary_error = best_match(all_errors)
print(f"Primary issue: {primary_error.message}")
# Navigate specific path errors
if "profile" in error_tree:
profile_errors = error_tree["profile"]
for field in ["name", "email", "age"]:
if field in profile_errors:
field_errors = profile_errors[field]
print(f"{field} errors: {len(field_errors)}")
for error in field_errors:
print(f" - {error.message}")from jsonschema import Draft7Validator, ValidationError
def detailed_error_report(validator, data):
"""Generate detailed error report with context."""
errors = []
for error in validator.iter_errors(data):
error_info = {
'path': '.'.join(str(p) for p in error.path),
'message': error.message,
'invalid_value': error.instance,
'validator': error.validator,
'schema_rule': error.validator_value,
'schema_path': '.'.join(error.schema_path)
}
errors.append(error_info)
return errors
# Usage
schema = {"type": "integer", "minimum": 0, "maximum": 100}
validator = Draft7Validator(schema)
report = detailed_error_report(validator, -5)
for error in report:
print(f"Path: {error['path']}")
print(f"Error: {error['message']}")
print(f"Invalid value: {error['invalid_value']}")
print(f"Rule: {error['validator']} = {error['schema_rule']}")
print("---")from typing import Any, Callable, Iterable, Iterator, SequenceInstall with Tessl CLI
npx tessl i tessl/pypi-types-jsonschema