JSONSchema

Language: Python

CLI/Utils

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

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.

Installation

pip: pip install jsonschema
conda: conda install -c conda-forge jsonschema

Usage

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.

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.

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.

Error Handling

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.