JSON Spec
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
- breaking The `json-spec` library primarily supports JSON Schema Draft 03 and Draft 04. This is a critical limitation as the JSON Schema specification has evolved significantly, with Draft 2020-12 being the latest standard. Users requiring features from newer drafts (e.g., Draft 07, 2019-09, 2020-12) will find this library insufficient or experience unexpected behavior.
- gotcha Common JSON syntax errors (e.g., trailing commas, unquoted object keys, single quotes instead of double quotes for strings, comments within JSON) will result in parsing failures. While not specific to `json-spec`, these are frequent mistakes when authoring JSON schemas or instances.
- gotcha The JSON Schema specification itself sometimes leaves certain behaviors 'undefined' leading to 'indeterminate' validation results. Different implementations of JSON Schema might resolve these ambiguities in varying ways, potentially leading to inconsistent validation outcomes across different tools or libraries.
Install
-
pip install json-spec -
pip install json-spec[cli] -
pip install json-spec[ip]
Imports
- load
from jsonspec.validators import load
- json_pointer
import jsonspec.pointer as json_pointer
- json_reference
import jsonspec.reference as json_reference
Quickstart
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}")