JSON Spec

0.12.0 · maintenance · verified Wed Apr 15

JSON Spec is a Python library that provides implementations for several JSON specifications, including JSON Schema (specifically Draft 03 and Draft 04), JSON Pointer, and JSON Reference. The current version is 0.12.0, with the last release approximately two years ago. While not actively updated to support the latest JSON Schema drafts, it remains a functional tool for applications requiring adherence to its supported specifications.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a JSON Schema, create a validator using `jsonspec.validators.load`, and validate JSON instances against it. It also includes a basic example of using JSON Pointer to extract a value from a JSON document. The `load` function defaults to JSON Schema Draft 04, but can be explicitly set to Draft 03 if needed.

from jsonspec.validators import load
from jsonspec.pointer import Pointer

# Define a JSON Schema (defaults to Draft 04)
schema = {
    'title': 'Example Schema',
    'type': 'object',
    'properties': {
        'name': {'type': 'string'},
        'age': {'type': 'integer', 'minimum': 0}
    },
    'required': ['name', 'age']
}

# Compile the schema into a validator
validator = load(schema)

# Instance to validate
valid_instance = {'name': 'Alice', 'age': 30}
invalid_instance = {'name': 'Bob', 'age': -5}
missing_field_instance = {'name': 'Charlie'}

# Perform validation
try:
    validator.validate(valid_instance)
    print("Valid instance is valid.")
except Exception as e:
    print(f"Valid instance failed validation: {e}")

try:
    validator.validate(invalid_instance)
    print("Invalid instance (negative age) is valid.")
except Exception as e:
    print(f"Invalid instance (negative age) failed validation: {e}")

try:
    validator.validate(missing_field_instance)
    print("Invalid instance (missing field) is valid.")
except Exception as e:
    print(f"Invalid instance (missing field) failed validation: {e}")

# Example of JSON Pointer (requires explicit import/use)
data_for_pointer = {'foo': ['bar', 'baz', {'qux': 10}]}
pointer = Pointer('/foo/2/qux')
value = pointer.get(data_for_pointer)
print(f"Value at /foo/2/qux: {value}")

view raw JSON →