JSONSchema Spec
jsonschema-spec is a Python library (current version 0.4.5) that provides object-oriented paths for traversing and accessing JSON Schemas. It allows developers to interact with schema elements and their references in a programmatic way, abstracting away raw dictionary manipulation. The library sees active development, with frequent patch releases and minor updates to enhance features and ensure compatibility with related tools.
Warnings
- breaking The `SchemaAccessor.resolver` interface underwent changes that affected backward compatibility. If you were directly interacting with or extending `SchemaAccessor.resolver` in versions prior to `0.4.5`, your code might break.
- gotcha The resolved-path cache, which can significantly improve performance for repeated schema lookups, is disabled by default. For performance-critical applications with frequent schema path traversals, enabling this cache is highly recommended.
- gotcha While `jsonschema-spec` provides robust schema traversal, the underlying JSON Schema specification itself has introduced breaking changes between its different drafts (e.g., Draft 2019-09 to Draft 2020-12). These changes can alter the interpretation and validation behavior of schemas, even if `jsonschema-spec` correctly parses the structure.
Install
-
pip install jsonschema-spec
Imports
- SchemaPath
from jsonschema_spec import SchemaPath
- SchemaAccessor
from jsonschema_spec import SchemaAccessor
Quickstart
from jsonschema_spec import SchemaPath
# Define a simple JSON Schema
schema_dict = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"$defs": {
"Person": {
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"}
}
}
},
"$ref": "#/$defs/Person"
}
# Create a SchemaPath object from the dictionary
path = SchemaPath.from_dict(schema_dict)
# Traverse the schema using path-like access
name_prop_path = path / "properties" / "name"
print(f"Name property schema: {name_prop_path.get_value()}")
# Expected: {'type': 'string'}
# Access a definition using implicit dereferencing
person_def_path = path / '$defs' / 'Person'
print(f"Person definition schema: {person_def_path.get_value()}")
# Expected: {'type': 'object', 'properties': {'firstName': {'type': 'string'}, 'lastName': {'type': 'string'}}}
# Directly dereference the root '$ref'
dereferenced_root = path.dereference()
print(f"Dereferenced root schema type: {dereferenced_root.get_value()['type']}")
# Expected: object
# Check for keys
print(f"'properties' in root path: {'properties' in path}")
# Expected: True