JSON Schema to Python
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
- gotcha The PyPI metadata specifies `requires_python >= 2.7`, implying the generator itself can run on older Python interpreters. However, for optimal compatibility with modern type-hinting, language features, and to avoid potential issues, it is strongly recommended to run `jschema-to-python` with Python 3.8+.
- gotcha The `generate_code` function returns the Python code as a plain string. It does not automatically write this string to a file or manage your project's file structure. Users must explicitly save the output to a `.py` file for it to be importable and runnable as a module.
- gotcha By default, `jschema-to-python` attempts to format the generated code using a code formatter (like Black, if available). If you experience unexpected formatting, conflicts with your project's existing linters, or prefer manual formatting, you can disable this behavior using `CodeGeneratorOptions(disable_formatter=True)`. This will result in unformatted, but functionally correct, code.
Install
-
pip install jschema-to-python
Imports
- generate_code
from jschema_to_python import generate_code
- generate_code_from_file
from jschema_to_python import generate_code_from_file
- CodeGeneratorOptions
from jschema_to_python.code_generator_options import CodeGeneratorOptions
Quickstart
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)