Python JSON Schema Grammar Interpreter

0.12.3 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart defines a simple 'Person' JSON Schema using `pyjsg` decorators, creates a validator, and demonstrates validating both valid and invalid data against it. It also shows how to access the validated data as a Python object and dump it back to a dictionary.

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}")

view raw JSON →