0
# JSON Schema Validation
1
2
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.
3
4
## Capabilities
5
6
### Validation Function
7
8
Main validation function that validates an instance against a JSON schema with automatic validator selection.
9
10
```python { .api }
11
def validate(
12
instance: Any,
13
schema: dict,
14
cls: type | None = None,
15
*args,
16
**kwargs
17
) -> None:
18
"""
19
Validate an instance against a schema.
20
21
Args:
22
instance: The data to validate
23
schema: The JSON schema to validate against
24
cls: Validator class to use (auto-selected if None)
25
*args: Additional arguments for validator
26
**kwargs: Additional keyword arguments for validator
27
28
Raises:
29
ValidationError: If validation fails
30
SchemaError: If schema is invalid
31
"""
32
```
33
34
Usage example:
35
36
```python
37
from jsonschema import validate, ValidationError
38
39
schema = {"type": "string", "minLength": 5}
40
data = "hello"
41
42
try:
43
validate(data, schema)
44
print("Valid!")
45
except ValidationError as e:
46
print(f"Invalid: {e.message}")
47
```
48
49
### Validator Selection
50
51
Get the appropriate validator class for a given schema.
52
53
```python { .api }
54
def validator_for(schema: dict, default: type | None = None) -> type:
55
"""
56
Get the appropriate validator class for a schema.
57
58
Args:
59
schema: JSON schema
60
default: Default validator class if none found
61
62
Returns:
63
Validator class appropriate for the schema
64
"""
65
```
66
67
### Draft 3 Validator
68
69
Validator for JSON Schema Draft 3 specification.
70
71
```python { .api }
72
class Draft3Validator:
73
"""JSON Schema Draft 3 validator."""
74
75
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
76
77
def check_schema(self, schema: dict) -> None:
78
"""Check if a schema is valid."""
79
80
def is_type(self, instance: Any, type: str) -> bool:
81
"""Check if instance is of the given type."""
82
83
def is_valid(self, instance: Any) -> bool:
84
"""Check if instance is valid against the schema."""
85
86
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
87
"""Iterate over validation errors for an instance."""
88
89
def validate(self, instance: Any) -> None:
90
"""Validate an instance, raising ValidationError on failure."""
91
92
def evolve(self, **kwargs) -> Draft3Validator:
93
"""Create a new validator with modified parameters."""
94
```
95
96
### Draft 4 Validator
97
98
Validator for JSON Schema Draft 4 specification.
99
100
```python { .api }
101
class Draft4Validator:
102
"""JSON Schema Draft 4 validator."""
103
104
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
105
106
def check_schema(self, schema: dict) -> None:
107
"""Check if a schema is valid."""
108
109
def is_type(self, instance: Any, type: str) -> bool:
110
"""Check if instance is of the given type."""
111
112
def is_valid(self, instance: Any) -> bool:
113
"""Check if instance is valid against the schema."""
114
115
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
116
"""Iterate over validation errors for an instance."""
117
118
def validate(self, instance: Any) -> None:
119
"""Validate an instance, raising ValidationError on failure."""
120
121
def evolve(self, **kwargs) -> Draft4Validator:
122
"""Create a new validator with modified parameters."""
123
```
124
125
### Draft 6 Validator
126
127
Validator for JSON Schema Draft 6 specification.
128
129
```python { .api }
130
class Draft6Validator:
131
"""JSON Schema Draft 6 validator."""
132
133
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
134
135
def check_schema(self, schema: dict) -> None:
136
"""Check if a schema is valid."""
137
138
def is_type(self, instance: Any, type: str) -> bool:
139
"""Check if instance is of the given type."""
140
141
def is_valid(self, instance: Any) -> bool:
142
"""Check if instance is valid against the schema."""
143
144
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
145
"""Iterate over validation errors for an instance."""
146
147
def validate(self, instance: Any) -> None:
148
"""Validate an instance, raising ValidationError on failure."""
149
150
def evolve(self, **kwargs) -> Draft6Validator:
151
"""Create a new validator with modified parameters."""
152
```
153
154
### Draft 7 Validator
155
156
Validator for JSON Schema Draft 7 specification (most commonly used).
157
158
```python { .api }
159
class Draft7Validator:
160
"""JSON Schema Draft 7 validator."""
161
162
def __init__(self, schema: dict, resolver: RefResolver | None = None, format_checker: FormatChecker | None = None) -> None: ...
163
164
def check_schema(self, schema: dict) -> None:
165
"""Check if a schema is valid."""
166
167
def is_type(self, instance: Any, type: str) -> bool:
168
"""Check if instance is of the given type."""
169
170
def is_valid(self, instance: Any) -> bool:
171
"""Check if instance is valid against the schema."""
172
173
def iter_errors(self, instance: Any) -> Iterator[ValidationError]:
174
"""Iterate over validation errors for an instance."""
175
176
def validate(self, instance: Any) -> None:
177
"""Validate an instance, raising ValidationError on failure."""
178
179
def evolve(self, **kwargs) -> Draft7Validator:
180
"""Create a new validator with modified parameters."""
181
```
182
183
Usage example:
184
185
```python
186
from jsonschema import Draft7Validator
187
188
schema = {
189
"type": "object",
190
"properties": {
191
"name": {"type": "string"},
192
"age": {"type": "integer", "minimum": 0}
193
},
194
"required": ["name"]
195
}
196
197
validator = Draft7Validator(schema)
198
199
# Check if data is valid
200
data = {"name": "Alice", "age": 25}
201
if validator.is_valid(data):
202
print("Valid!")
203
204
# Get all validation errors
205
invalid_data = {"age": -5}
206
for error in validator.iter_errors(invalid_data):
207
print(f"Error at {'.'.join(str(p) for p in error.path)}: {error.message}")
208
```
209
210
### Reference Resolution
211
212
System for resolving JSON Schema references ($ref) to enable schema composition and reuse.
213
214
```python { .api }
215
class RefResolver:
216
"""Resolver for JSON Schema references."""
217
218
referrer: dict
219
cache_remote: bool
220
handlers: dict
221
store: dict
222
223
def __init__(
224
self,
225
base_uri: str,
226
referrer: dict,
227
store: dict | None = None,
228
cache_remote: bool = True,
229
handlers: dict | None = None,
230
urljoin_cache: dict | None = None,
231
remote_cache: dict | None = None
232
) -> None:
233
"""
234
Initialize reference resolver.
235
236
Args:
237
base_uri: Base URI for resolving relative references
238
referrer: Schema being resolved
239
store: Pre-loaded schema store
240
cache_remote: Whether to cache remote schemas
241
handlers: Custom URI handlers
242
urljoin_cache: Cache for URI joining operations
243
remote_cache: Cache for remote schema retrieval
244
"""
245
246
@classmethod
247
def from_schema(cls, schema: dict, id_of: Callable = None, *args, **kwargs) -> RefResolver:
248
"""Create resolver from a schema."""
249
250
def push_scope(self, scope: str) -> None:
251
"""Push a new resolution scope."""
252
253
def pop_scope(self) -> None:
254
"""Pop the current resolution scope."""
255
256
@property
257
def resolution_scope(self) -> str:
258
"""Current resolution scope."""
259
260
@property
261
def base_uri(self) -> str:
262
"""Base URI for resolution."""
263
264
def in_scope(self, scope: str) -> ContextManager[None]:
265
"""Context manager for temporary scope changes."""
266
267
def resolving(self, ref: str) -> ContextManager[tuple]:
268
"""Context manager for resolving a reference."""
269
270
def resolve(self, ref: str) -> tuple:
271
"""
272
Resolve a reference.
273
274
Args:
275
ref: Reference to resolve
276
277
Returns:
278
(resolved_url, resolved_schema) tuple
279
"""
280
281
def resolve_from_url(self, url: str) -> tuple:
282
"""Resolve from a URL."""
283
284
def resolve_fragment(self, document: dict, fragment: str) -> Any:
285
"""Resolve a fragment within a document."""
286
287
def resolve_remote(self, uri: str) -> dict:
288
"""Resolve a remote schema."""
289
```
290
291
Usage example:
292
293
```python
294
from jsonschema import RefResolver, Draft7Validator
295
296
# Schema with references
297
main_schema = {
298
"type": "object",
299
"properties": {
300
"person": {"$ref": "#/definitions/person"}
301
},
302
"definitions": {
303
"person": {
304
"type": "object",
305
"properties": {
306
"name": {"type": "string"},
307
"age": {"type": "integer"}
308
}
309
}
310
}
311
}
312
313
resolver = RefResolver.from_schema(main_schema)
314
validator = Draft7Validator(main_schema, resolver=resolver)
315
316
data = {"person": {"name": "Bob", "age": 30}}
317
validator.validate(data) # Will resolve the $ref automatically
318
```
319
320
### Custom Validator Creation
321
322
Create custom validator classes with specific validation rules.
323
324
```python { .api }
325
def create(
326
meta_schema: dict,
327
validators: dict | None = None,
328
version: str | None = None,
329
default_types: dict | None = None,
330
type_checker: TypeChecker | None = None,
331
id_of: Callable | None = None
332
) -> type:
333
"""
334
Create a custom validator class.
335
336
Args:
337
meta_schema: Meta-schema for the validator
338
validators: Custom validation functions
339
version: Version identifier
340
default_types: Default type definitions
341
type_checker: Type checker instance
342
id_of: Function to extract schema ID
343
344
Returns:
345
New validator class
346
"""
347
348
def extend(
349
validator: type,
350
validators: dict | None = None,
351
version: str | None = None,
352
type_checker: TypeChecker | None = None
353
) -> type:
354
"""
355
Extend an existing validator class.
356
357
Args:
358
validator: Base validator class to extend
359
validators: Additional validation functions
360
version: Version identifier
361
type_checker: Type checker instance
362
363
Returns:
364
Extended validator class
365
"""
366
367
def validates(version: str) -> Callable:
368
"""
369
Decorator for registering validation functions.
370
371
Args:
372
version: JSON Schema version
373
374
Returns:
375
Decorator function
376
"""
377
```
378
379
### Module Variables
380
381
Access to validator registry and meta-schemas for different JSON Schema drafts.
382
383
```python { .api }
384
# Dictionary of available validators by draft version
385
validators: dict[str, type]
386
387
# Dictionary of meta-schemas for each JSON Schema draft
388
meta_schemas: dict[str, dict]
389
```
390
391
Usage example:
392
393
```python
394
from jsonschema.validators import validators, meta_schemas
395
396
# Access available validators
397
draft7_validator_class = validators.get('draft7')
398
399
# Access meta-schemas
400
draft7_meta_schema = meta_schemas.get('draft7')
401
print(f"Meta-schema title: {draft7_meta_schema.get('title', 'Unknown')}")
402
```
403
404
## Types
405
406
```python { .api }
407
from typing import Any, Callable, ContextManager, Iterator, dict
408
from jsonschema.exceptions import ValidationError
409
from jsonschema._format import FormatChecker
410
from jsonschema._types import TypeChecker
411
```