JSON Schema to Python

1.2.3 · active · verified Sat Apr 11

jschema-to-python is a utility that generates Python source code for data classes directly from a JSON schema. As of version 1.2.3, it provides functionality to translate schema definitions into Python classes, complete with type hints and properties. The library, maintained by Microsoft, has an irregular release cadence, typically driven by internal needs or significant updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a JSON schema, use `jschema_to_python.generate_code` to convert it into a Python class string, and then explicitly write that string to a `.py` file. It also shows how to configure `CodeGeneratorOptions` to influence the generated code's style.

import json
from jschema_to_python import generate_code
from jschema_to_python.code_generator_options import CodeGeneratorOptions
import os

# Define a simple JSON schema for a Product
schema = {
    "title": "Product",
    "type": "object",
    "properties": {
        "id": {"type": "string", "description": "Unique product identifier"},
        "name": {"type": "string"},
        "price": {"type": "number"},
        "is_available": {"type": "boolean"}
    },
    "required": ["id", "name", "price"]
}

# Configure generator options (optional - defaults are often fine)
options = CodeGeneratorOptions(
    disable_formatter=False, # Keep formatting enabled by default
    use_union_for_required_and_optional=True # Use Union[Type, None] for optional fields
)

# Generate Python code as a string
module_name = 'product_model'
generated_code_string = generate_code(schema, module_name, options)

# To make the generated code importable, write it to a .py file
output_filename = f'{module_name}.py'
with open(output_filename, 'w') as f:
    f.write(generated_code_string)

print(f"Generated code successfully written to {output_filename}:")
print("---\n" + generated_code_string + "\n---")

# You can now import and use the generated class:
# from product_model import Product
# my_product = Product(id="P123", name="Example Item", price=29.99, is_available=True)
# print(my_product.to_dict())

# Clean up the generated file for demonstration purposes (uncomment to enable)
# os.remove(output_filename)

view raw JSON →