Python JSONSchema Objects

0.5.7 · active · verified Thu Apr 16

python-jsonschema-objects is an active Python library (version 0.5.7) that provides automatic class-based binding to JSON Schemas, generating Python objects with built-in validation. It aims to reduce the tedium of writing object bindings for JSON schemas by auto-generating classes that seamlessly encode to and from JSON, complete with validations. The library has a moderate release cadence, with the last release in November 2024.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a JSON Schema, build Python classes from it using `ObjectBuilder`, instantiate a generated class, and observe built-in validation upon property assignment. It also shows how to serialize the object back to JSON.

import python_jsonschema_objects as pjs
import json

schema_str = '''
{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "firstName": {"type": "string"},
    "lastName": {"type": "string"},
    "age": {"description": "Age in years", "type": "integer", "minimum": 0},
    "dogs": {"type": "array", "items": {"type": "string"}, "maxItems": 4}
  },
  "required": ["firstName", "lastName"]
}
'''
schema = json.loads(schema_str)

builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()

# Access the generated class by its title
Person = ns.ExampleSchema

# Create an instance and set properties
james = Person(firstName="James", lastName="Bond")
print(f"Created person: {james.firstName} {james.lastName}")

# Properties are validated on assignment
try:
    james.age = -2
except pjs.ValidationError as e:
    print(f"Validation error: {e.message}")

try:
    james.dogs = ["Jasper", "Spot", "Noodles", "Fido", "Dumbo"]
except pjs.ValidationError as e:
    print(f"Validation error: {e.message}")

# Serialize the object to JSON
json_output = james.serialize(sort_keys=True)
print(f"Serialized object: {json_output}")

view raw JSON →