or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-validation.mderror-handling.mdformat-validation.mdindex.mdtype-checking.mdvalidator-creation.mdvalidators.md
tile.json

tessl/pypi-jsonschema

An implementation of JSON Schema validation for Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/jsonschema@4.25.x

To install, run

npx @tessl/cli install tessl/pypi-jsonschema@4.25.0

index.mddocs/

jsonschema

A 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.

Package Information

  • Package Name: jsonschema
  • Language: Python
  • Installation: pip install jsonschema
  • Optional Dependencies: pip install jsonschema[format] for format validation

Core Imports

import jsonschema

Common imports for validation:

from jsonschema import validate, ValidationError, Draft202012Validator

For format validation:

from jsonschema import FormatChecker

Basic Usage

from 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}")

Architecture

jsonschema is built around a modular architecture with key components:

  • Validator Classes: Draft-specific implementations (Draft3Validator through Draft202012Validator)
  • Validation Engine: Core validation logic with keyword-based validation functions
  • Type System: JSON Schema type checking with extensible TypeChecker classes
  • Format System: Format validation with extensible FormatChecker classes
  • Error Reporting: Comprehensive error details with path information and error trees
  • Reference Resolution: Support for JSON references ($ref) using the referencing library

This design enables precise JSON Schema compliance, extensive customization capabilities, and integration with various Python frameworks and applications.

Capabilities

Core Validation

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): ...

Core Validation

Validator Classes

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: ...

Validator Classes

Error Handling

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): ...

Error Handling

Format Validation

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: FormatChecker

Format Validation

Type Checking

Customizable 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: TypeChecker

Type Checking

Validator Creation

Advanced 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): ...

Validator Creation

Types

Core Types

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]

Exception Types

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."""