What it is
JSONSchema is a Python library for validating JSON data against a schema. It allows developers to ensure that JSON objects conform to a defined structure, including types, required properties, and value constraints.
JSONSchema allows you to define schemas using Python dictionaries and validate JSON-like data structures. It supports type checking, pattern validation, required properties, nested structures, and custom validation functions.
Installation
pip install jsonschemaGetting started
The smallest useful thing you can do with it, and what each part means.
from jsonschema import validate, ValidationError
schema = {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'age': {'type': 'number'},
},
'required': ['name', 'age']
}
data = {'name': 'Alice', 'age': 30}
try:
validate(instance=data, schema=schema)
print('JSON is valid')
except ValidationError as e:
print('JSON is invalid:', e)data = {'name': 'Alice'}
try:
validate(instance=data, schema=schema)
except ValidationError as e:
print('Validation error:', e.message)Advanced usage
Where the library earns its place over a simpler alternative.
schema = {
'type': 'object',
'properties': {
'user': {
'type': 'object',
'properties': {
'id': {'type': 'integer'},
'name': {'type': 'string'}
},
'required': ['id', 'name']
}
},
'required': ['user']
}
data = {'user': {'id': 1, 'name': 'Alice'}}
validate(instance=data, schema=schema)schema = {
'type': 'object',
'properties': {
'email': {'type': 'string', 'pattern': r'^[\w\.-]+@[\w\.-]+\.\w+$'}
},
'required': ['email']
}
data = {'email': 'alice@example.com'}
validate(instance=data, schema=schema)schema = {
'type': 'object',
'properties': {
'role': {'type': 'string', 'enum': ['admin', 'user', 'guest']}
},
'required': ['role']
}
data = {'role': 'admin'}
validate(instance=data, schema=schema)schema = {
'type': 'object',
'properties': {
'tags': {'type': 'array', 'items': {'type': 'string'}, 'minItems': 1}
},
'required': ['tags']
}
data = {'tags': ['python', 'json']}
validate(instance=data, schema=schema)from jsonschema import Draft7Validator
def is_positive(validator, value, instance, schema):
if instance <= 0:
yield ValidationError('Value must be positive')
validator = Draft7Validator(schema={'type': 'number'}, validators={'positive': is_positive})
for error in validator.iter_errors(-5):
print(error.message)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- jsonschema.exceptions.ValidationError
- Raised when the instance does not conform to the schema. Check the error message to identify which property is invalid.
- jsonschema.exceptions.SchemaError
- Raised when the schema itself is invalid. Ensure the schema follows the JSON Schema specification.
Best practices
- Define schemas as Python dictionaries or load from JSON files.
- Use Draft7Validator or later for more advanced schema features.
- Validate user inputs in APIs and configurations to prevent errors.
- Combine with try/except blocks to handle invalid data gracefully.
- Use patterns, enums, and `required` properties to enforce strict data validation.
Background
Why it exists, and what it was reacting to.
JSONSchema was created to provide a standard way of validating JSON data in Python. It is widely used in API development, configuration validation, and data exchange scenarios where ensuring consistent JSON structure is critical. It adheres to the JSON Schema standard (drafts 4, 6, and 7).
