0
# jsonschema
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: jsonschema
7
- **Language**: Python
8
- **Installation**: `pip install jsonschema`
9
- **Optional Dependencies**: `pip install jsonschema[format]` for format validation
10
11
## Core Imports
12
13
```python
14
import jsonschema
15
```
16
17
Common imports for validation:
18
19
```python
20
from jsonschema import validate, ValidationError, Draft202012Validator
21
```
22
23
For format validation:
24
25
```python
26
from jsonschema import FormatChecker
27
```
28
29
## Basic Usage
30
31
```python
32
from jsonschema import validate, ValidationError
33
34
# Define a schema
35
schema = {
36
"type": "object",
37
"properties": {
38
"name": {"type": "string"},
39
"age": {"type": "number"},
40
"email": {"type": "string", "format": "email"}
41
},
42
"required": ["name", "age"]
43
}
44
45
# Valid data
46
data = {"name": "John Doe", "age": 30, "email": "john@example.com"}
47
48
try:
49
validate(instance=data, schema=schema)
50
print("Data is valid!")
51
except ValidationError as e:
52
print(f"Validation failed: {e.message}")
53
54
# Using a specific validator class
55
from jsonschema import Draft202012Validator
56
57
validator = Draft202012Validator(schema)
58
if validator.is_valid(data):
59
print("Valid!")
60
else:
61
for error in validator.iter_errors(data):
62
print(f"Error: {error.message}")
63
```
64
65
## Architecture
66
67
jsonschema is built around a modular architecture with key components:
68
69
- **Validator Classes**: Draft-specific implementations (Draft3Validator through Draft202012Validator)
70
- **Validation Engine**: Core validation logic with keyword-based validation functions
71
- **Type System**: JSON Schema type checking with extensible TypeChecker classes
72
- **Format System**: Format validation with extensible FormatChecker classes
73
- **Error Reporting**: Comprehensive error details with path information and error trees
74
- **Reference Resolution**: Support for JSON references ($ref) using the referencing library
75
76
This design enables precise JSON Schema compliance, extensive customization capabilities, and integration with various Python frameworks and applications.
77
78
## Capabilities
79
80
### Core Validation
81
82
Essential validation functionality including the main validate function, validator creation, and schema compliance checking.
83
84
```python { .api }
85
def validate(instance, schema, cls=None, *args, **kwargs): ...
86
def validator_for(schema, default=_UNSET): ...
87
```
88
89
[Core Validation](./core-validation.md)
90
91
### Validator Classes
92
93
Draft-specific validator implementations providing full compliance with each JSON Schema specification version, from Draft 3 through Draft 2020-12.
94
95
```python { .api }
96
class Draft202012Validator:
97
def __init__(self, schema, registry=None, resolver=None, format_checker=None): ...
98
def validate(self, instance): ...
99
def is_valid(self, instance): ...
100
def iter_errors(self, instance): ...
101
102
class Draft201909Validator: ...
103
class Draft7Validator: ...
104
class Draft6Validator: ...
105
class Draft4Validator: ...
106
class Draft3Validator: ...
107
```
108
109
[Validator Classes](./validators.md)
110
111
### Error Handling
112
113
Comprehensive error reporting with detailed validation failure information, error trees for complex validation scenarios, and utilities for finding the most relevant errors.
114
115
```python { .api }
116
class ValidationError(Exception):
117
def __init__(self, message, validator=None, path=(), context=(), ...): ...
118
@property
119
def message: str
120
@property
121
def path: deque
122
@property
123
def schema_path: deque
124
125
class SchemaError(Exception): ...
126
class ErrorTree: ...
127
128
def best_match(errors, key=None): ...
129
```
130
131
[Error Handling](./error-handling.md)
132
133
### Format Validation
134
135
Extensible format checking system supporting built-in formats like email, URI, date-time, and custom format validators.
136
137
```python { .api }
138
class FormatChecker:
139
def __init__(self, formats=None): ...
140
def check(self, instance, format): ...
141
def checks(self, format, raises=()): ...
142
143
# Built-in format checkers
144
draft202012_format_checker: FormatChecker
145
draft201909_format_checker: FormatChecker
146
draft7_format_checker: FormatChecker
147
draft6_format_checker: FormatChecker
148
draft4_format_checker: FormatChecker
149
draft3_format_checker: FormatChecker
150
```
151
152
[Format Validation](./format-validation.md)
153
154
### Type Checking
155
156
Customizable type checking system for JSON Schema types with built-in type checkers for each draft version and extensibility for custom type definitions.
157
158
```python { .api }
159
class TypeChecker:
160
def __init__(self, type_checkers=()): ...
161
def is_type(self, instance, type): ...
162
def redefine(self, type, fn): ...
163
def redefine_many(self, definitions=()): ...
164
def remove(self, *types): ...
165
166
# Built-in type checkers
167
draft202012_type_checker: TypeChecker
168
draft201909_type_checker: TypeChecker
169
draft7_type_checker: TypeChecker
170
draft6_type_checker: TypeChecker
171
draft4_type_checker: TypeChecker
172
draft3_type_checker: TypeChecker
173
```
174
175
[Type Checking](./type-checking.md)
176
177
### Validator Creation
178
179
Advanced validator creation and extension capabilities for building custom validators, extending existing ones, and registering new schema versions.
180
181
```python { .api }
182
def create(meta_schema, validators=(), version=None, type_checker=None, format_checker=None, id_of=None, applicable_validators=None): ...
183
def extend(validator, validators=(), version=None, type_checker=None, format_checker=None): ...
184
def validates(version): ...
185
```
186
187
[Validator Creation](./validator-creation.md)
188
189
## Types
190
191
### Core Types
192
193
```python { .api }
194
from typing import Any, Iterable, Mapping, Callable
195
from collections.abc import Sequence
196
from collections import deque
197
198
# Schema types
199
Schema = Mapping[str, Any] | bool
200
201
# Validation function signature
202
SchemaKeywordValidator = Callable[[Validator, Any, Any, Schema], Iterable[ValidationError]]
203
204
# Path types
205
PathType = deque[str | int]
206
```
207
208
### Exception Types
209
210
```python { .api }
211
class UndefinedTypeCheck(Exception):
212
"""Raised when an undefined type is used in type checking."""
213
214
class UnknownType(Exception):
215
"""Raised when an unknown type is encountered."""
216
217
class FormatError(Exception):
218
"""Raised when format validation fails."""
219
```