High-performance JSON schema validation library for Python with support for JSON Schema drafts 04, 06, and 07.
npx @tessl/cli install tessl/pypi-fastjsonschema@2.21.0A high-performance JSON schema validation library for Python that implements JSON Schema drafts 04, 06, and 07. It generates optimized validation code on-the-fly to achieve exceptional performance, being significantly faster than popular alternatives like jsonschema and json-spec.
pip install fastjsonschemaimport fastjsonschemaCommon imports for validation:
from fastjsonschema import compile, validate, JsonSchemaValueExceptionimport fastjsonschema
# Define a JSON schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0},
"email": {"type": "string", "format": "email"}
},
"required": ["name", "age"],
"additionalProperties": False
}
# Method 1: Compile for reuse (recommended for performance)
validate_person = fastjsonschema.compile(schema)
try:
# Valid data
result = validate_person({"name": "John", "age": 30, "email": "john@example.com"})
print("Valid:", result)
# Invalid data will raise an exception
validate_person({"name": "John", "age": -5})
except fastjsonschema.JsonSchemaValueException as e:
print(f"Validation error: {e.message}")
print(f"Invalid value: {e.value}")
print(f"Path: {e.path}")
# Method 2: One-time validation (less performant)
try:
fastjsonschema.validate(schema, {"name": "Jane", "age": 25})
except fastjsonschema.JsonSchemaValueException as e:
print(f"Validation failed: {e}")Fastjsonschema works by generating optimized Python validation code based on the provided JSON schema. The library supports:
Compiles JSON schemas into optimized validation functions for maximum performance when validating multiple data instances.
def compile(definition, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
"""
Generates validation function for validating JSON schema passed in definition.
Args:
definition (dict): JSON schema definition
handlers (dict): Mapping from URI to function for retrieving remote schemas
formats (dict): Custom format validators (regex strings or callables)
use_default (bool): Apply default values from schema (default: True)
use_formats (bool): Use format assertions (default: True)
detailed_exceptions (bool): Include detailed error information (default: True)
Returns:
function: Compiled validation function that takes data and returns validated data
Raises:
JsonSchemaDefinitionException: When schema compilation fails
"""Validates data against a schema in a single call, suitable for occasional validations where performance is not critical.
def validate(definition, data, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
"""
Validation function for lazy programmers or for use cases when you need
to call validation only once.
Args:
definition (dict): JSON schema definition
data: Data to validate against the schema
handlers (dict): Mapping from URI to function for retrieving remote schemas
formats (dict): Custom format validators (regex strings or callables)
use_default (bool): Apply default values from schema (default: True)
use_formats (bool): Use format assertions (default: True)
detailed_exceptions (bool): Include detailed error information (default: True)
Returns:
Validated data (potentially with defaults applied)
Raises:
JsonSchemaValueException: When validation fails
JsonSchemaDefinitionException: When schema compilation fails
"""Generates validation code as a string that can be saved to files for even better performance or standalone deployment.
def compile_to_code(definition, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True):
"""
Generates validation code for validating JSON schema passed in definition.
Args:
definition (dict): JSON schema definition
handlers (dict): Mapping from URI to function for retrieving remote schemas
formats (dict): Custom format validators (regex strings or callables)
use_default (bool): Apply default values from schema (default: True)
use_formats (bool): Use format assertions (default: True)
detailed_exceptions (bool): Include detailed error information (default: True)
Returns:
str: Python code string containing validation function
Raises:
JsonSchemaDefinitionException: When schema compilation fails
"""Generate validation code directly from the command line using the built-in CLI interface.
# Generate validation code from schema passed as argument
python -m fastjsonschema '{"type": "string", "minLength": 5}' > validator.py
# Generate validation code from schema via stdin
echo '{"type": "number", "maximum": 100}' | python -m fastjsonschema > validator.py
# Use with files
python -m fastjsonschema "$(cat schema.json)" > validator.pyThe generated code can then be imported and used directly:
# Content of generated validator.py file
from validator import validate_data
try:
result = validate_data("hello world") # Valid
print("Valid:", result)
except Exception as e:
print("Invalid:", e)Support for custom format validation through regular expressions or callable functions.
# Using regular expressions
custom_formats = {
'custom-id': r'^[A-Z]{2}-\d{4}$', # e.g., "AB-1234"
}
# Using callable functions
def validate_phone(value):
"""Custom phone number validator"""
if not isinstance(value, str):
return False
# Remove spaces and dashes
cleaned = value.replace(' ', '').replace('-', '')
return cleaned.isdigit() and len(cleaned) == 10
custom_formats = {
'phone': validate_phone
}
# Use with compile
validator = fastjsonschema.compile(schema, formats=custom_formats)Handle external schema references through custom URI handlers.
def http_handler(uri):
"""Custom handler for HTTP URIs"""
import requests
response = requests.get(uri)
return response.json()
handlers = {
'http': http_handler,
'https': http_handler
}
# Schema with remote reference
schema = {
"$ref": "https://json-schema.org/draft-07/schema#"
}
validator = fastjsonschema.compile(schema, handlers=handlers)Automatic application of default values specified in the schema.
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"status": {"type": "string", "default": "active"},
"count": {"type": "integer", "default": 0}
}
}
validator = fastjsonschema.compile(schema, use_default=True)
# Input data with missing optional fields
data = {"name": "John"}
# Validation applies defaults
result = validator(data)
# result = {"name": "John", "status": "active", "count": 0}Raised when data validation fails, providing detailed information about the validation error.
class JsonSchemaValueException(JsonSchemaException):
"""
Exception raised by validation function.
Attributes:
message (str): Human-readable information about the error
value: The invalid value that caused the exception
name (str): Path string in the data structure (e.g., "data.property[index]")
path (list): Path as array in the data structure (computed property)
definition (dict): The schema definition that failed
rule (str): The specific schema rule that was violated
rule_definition: The value of the violated rule (computed property)
"""Raised when schema compilation fails due to invalid or malformed schema.
class JsonSchemaDefinitionException(JsonSchemaException):
"""
Exception raised by generator of validation function when schema is invalid.
"""Base exception class for all fastjsonschema exceptions.
class JsonSchemaException(ValueError):
"""
Base exception of fastjsonschema library.
"""import fastjsonschema
schema = {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {"type": "number", "maximum": 100}
}
}
}
validator = fastjsonschema.compile(schema)
try:
validator({"items": [10, 50, 150, 75]})
except fastjsonschema.JsonSchemaValueException as e:
print(f"Error message: {e.message}")
print(f"Invalid value: {e.value}") # 150
print(f"Location path: {e.name}") # "data.items[2]"
print(f"Path array: {e.path}") # ["data", "items", "2"]
print(f"Violated rule: {e.rule}") # "maximum"
print(f"Rule value: {e.rule_definition}") # 100# For maximum performance, disable detailed exceptions
validator = fastjsonschema.compile(schema, detailed_exceptions=False)
# For even better performance, generate code to file
code = fastjsonschema.compile_to_code(schema)
with open('validator.py', 'w') as f:
f.write(code)
# Then import and use the generated validator
# from validator import validate_data# Schema draft is auto-detected from $schema field
draft04_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "string"
}
draft07_schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "string"
}
# If no $schema specified, defaults to draft-07
validator = fastjsonschema.compile({"type": "number"})VERSION = "2.21.2"Access the library version:
import fastjsonschema
print(fastjsonschema.VERSION) # "2.21.2"# Handler function type for remote schema resolution
def handler_function(uri: str) -> dict:
"""
Custom handler for resolving remote schema URIs.
Args:
uri: The URI to resolve
Returns:
dict: The resolved schema as a dictionary
"""
# Format validator function type
def format_validator(value: str) -> bool:
"""
Custom format validator function.
Args:
value: The string value to validate
Returns:
bool: True if valid, False otherwise. Can also raise exceptions.
"""
# Compiled validator function type
def validation_function(data) -> any:
"""
Compiled validation function returned by compile().
Args:
data: Data to validate against the compiled schema
Returns:
Validated data (potentially with defaults applied)
Raises:
JsonSchemaValueException: When validation fails
"""