Python JSON Schema Grammar Interpreter
pyjsg (Python JSON Schema Grammar interpreter) is a library that allows defining JSON schemas as Python classes and validating data against these generated structures. It provides tools to convert JSON Schema definitions into Python objects, facilitating type-safe data handling and validation within Python applications. The current stable version is 0.12.3, with releases occurring as features and bug fixes are implemented, typically not on a fixed schedule.
Common errors
-
pyjsg.jsg.JSGException: Unknown type or attribute in schema: 'patternProperties'
cause The JSON Schema keyword `patternProperties` or similar advanced features are not directly supported by `pyjsg`'s class generation mechanism.fixRefactor your schema to use `properties` or `additionalProperties` where possible, or handle `patternProperties` validation outside of `pyjsg`. -
pyjsg.validate.ValidationFailed: Value '...' does not conform to schema '...': Path: '$.age'. Expected type int, got str.
cause Input data does not match the expected type defined in the `pyjsg` schema for a specific field.fixEnsure your input data's types strictly adhere to the types specified in your `pyjsg` schema (e.g., `int`, `str`, `bool`). Convert data to the correct type before validation. -
AttributeError: 'Person' object has no attribute 'missing_field'
cause Attempting to access a field on a `pyjsg` object that was not part of the original validated input and doesn't have a default value in the schema.fixCheck if the field exists (e.g., `hasattr(obj, 'field')`) or ensure your schema defines all necessary fields and their optionality/defaults. Accessing non-existent fields without defaults will raise an `AttributeError`.
Warnings
- gotcha pyjsg interprets a subset of JSON Schema. Complex or non-standard JSON Schemas may not translate directly into `pyjsg` Python classes or validate as expected.
- breaking As a 0.x.x library, `pyjsg` may introduce breaking changes in minor versions (e.g., 0.11 to 0.12). API signatures, especially around schema definition and validation, can change.
- gotcha `pyjsg` generates Python classes from schemas. Direct manipulation of the raw `dict` output from `JSG_DUMP` or `JSG_LOAD` may lose type safety or fail validation if not re-instantiated through `pyjsg` classes.
Install
-
pip install pyjsg
Imports
- JSG
from pyjsg.jsg import JSG
- JSG_DUMP
from pyjsg.jsg import JSG_DUMP
- JSG_LOAD
from pyjsg.jsg import JSG_LOAD
- JSGValidate
from pyjsg.validate import JSGValidate
Quickstart
from pyjsg.jsg import JSG, JSG_DUMP
from pyjsg.validate import JSGValidate
# Define a JSON Schema using pyjsg decorators
@JSG(
jsg_name="Person",
jsg_uri="http://example.com/Person.jsg",
jsg_description="A simple person schema"
)
class Person:
name: str
age: int
isStudent: bool = False # Optional with default
# Example data
valid_person_data = {"name": "Alice", "age": 30}
invalid_person_data = {"name": "Bob", "age": "twenty"}
# Create a validator instance
validator = JSGValidate(Person)
# Validate valid data
try:
validated_person = validator.validate(valid_person_data)
print(f"Valid person: {validated_person}")
# Access validated data as a pyjsg object
print(f"Name: {validated_person.name}, Age: {validated_person.age}, Is Student: {validated_person.isStudent}")
print(f"Dumped valid person: {JSG_DUMP(validated_person)}")
except Exception as e:
print(f"Validation failed for valid data: {e}")
# Validate invalid data
try:
validator.validate(invalid_person_data)
print("Invalid person data somehow passed validation.")
except Exception as e:
print(f"Validation correctly failed for invalid data: {e}")