Skip to content

JSONSchema

Developer UtilitiesCLI/UtilsPython

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 jsonschema

Getting started

The smallest useful thing you can do with it, and what each part means.

Validating a simple JSON object
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)
Validates a Python dictionary against a schema specifying required properties and their types.
Invalid JSON object
data = {'name': 'Alice'}
try:
    validate(instance=data, schema=schema)
except ValidationError as e:
    print('Validation error:', e.message)
Demonstrates handling validation errors when required properties are missing.

Advanced usage

Where the library earns its place over a simpler alternative.

Nested JSON validation
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)
Validates nested dictionaries, ensuring inner objects also conform to a schema.
Using pattern validation
schema = {
    'type': 'object',
    'properties': {
        'email': {'type': 'string', 'pattern': r'^[\w\.-]+@[\w\.-]+\.\w+$'}
    },
    'required': ['email']
}
data = {'email': 'alice@example.com'}
validate(instance=data, schema=schema)
Ensures that string fields match a regular expression pattern, e.g., validating an email address.
Enum validation
schema = {
    'type': 'object',
    'properties': {
        'role': {'type': 'string', 'enum': ['admin', 'user', 'guest']}
    },
    'required': ['role']
}
data = {'role': 'admin'}
validate(instance=data, schema=schema)
Restricts a property to a set of predefined values using the `enum` keyword.
Array validation
schema = {
    'type': 'object',
    'properties': {
        'tags': {'type': 'array', 'items': {'type': 'string'}, 'minItems': 1}
    },
    'required': ['tags']
}
data = {'tags': ['python', 'json']}
validate(instance=data, schema=schema)
Validates array types, item types, and minimum number of items in the array.
Custom validator
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)
Demonstrates creating a custom validation function for specific constraints.

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