Skip to main content

ju

JSON Schema utilities: turn a Python function's signature into a JSON Schema and back, into a react-jsonschema-form spec for a web form, or into Pydantic models; and read an OpenAPI spec as a collection of routes.

Write the function once, and get its schema, its web form and its model instead of writing each by hand.

pip install ju

Documentation

Signature to JSON Schema, and back

>>> from ju import signature_to_json_schema, json_schema_to_signature
>>> def earth(north: str, south: bool, east: int = 1, west: float = 2.0):
...     """Earth docs"""
...     return f'{north=}, {south=}, {east=}, {west=}'
>>> schema = signature_to_json_schema(earth)
>>> assert schema == {
...     'description': 'Earth docs',
...     'title': 'earth',
...     'type': 'object',
...     'properties': {
...         'north': {'type': 'string'},
...         'south': {'type': 'boolean'},
...         'east': {'type': 'integer', 'default': 1},
...         'west': {'type': 'number', 'default': 2.0},
...     },
...     'required': ['north', 'south'],
... }
>>> sig = json_schema_to_signature(schema)  # an i2 Sig: an inspect.Signature that also carries a name and docs
>>> sig
<Sig (north: str, south: bool, east: int = 1, west: float = 2.0)>
>>> sig.name
'earth'
>>> sig.docs
'Earth docs'

A web form for a function (rjsf)

func_to_form_spec gives you a react-jsonschema-form specification for a function (try one in the rjsf playground):

>>> from ju import func_to_form_spec
>>> def foo(a_bool: bool, a_float=3.14, an_int=2, a_str: str = 'hello', something_else=None):
...     """A Foo function"""
>>> spec = func_to_form_spec(foo)
>>> spec['rjsf']['schema'] == {
...     'title': 'foo',
...     'type': 'object',
...     'properties': {
...         'a_bool': {'type': 'boolean'},
...         'a_float': {'type': 'number', 'default': 3.14},
...         'an_int': {'type': 'integer', 'default': 2},
...         'a_str': {'type': 'string', 'default': 'hello'},
...         'something_else': {'type': 'string', 'default': None},
...     },
...     'required': ['a_bool'],
...     'description': 'A Foo function',
... }
True
>>> spec['rjsf']['uiSchema']
{'ui:submitButtonOptions': {'submitText': 'Run'}, 'a_bool': {'ui:autofocus': True}}

The rest of spec['rjsf'] holds the form's options (liveValidate, disabled, showErrorList, ...).

OpenAPI routes

Routes reads an OpenAPI spec as a mapping of (method, endpoint) to Route objects:

>>> from ju import Routes
>>> spec = {
...     'openapi': '3.0.3',
...     'paths': {
...         '/items': {
...             'get': {'summary': 'List items', 'responses': {'200': {'description': 'An array of items'}}},
...             'post': {'summary': 'Create item', 'responses': {'201': {'description': 'Item created'}}},
...         }
...     },
... }
>>> routes = Routes(spec)
>>> list(routes)
[('get', '/items'), ('post', '/items')]
>>> r = routes['get', '/items']
>>> r
Route(method='get', endpoint='/items')
>>> r.method_data
{'summary': 'List items', 'responses': {'200': {'description': 'An array of items'}}}

openapi_to_funcs goes one step further and makes Python functions that call the routes.

pydantic utils

The ju.pydantic_util module provides comprehensive tools for working with Pydantic models and JSON schemas.

Creating Models from Data and Schemas

Generate Pydantic models dynamically from data or JSON schemas:

from ju.pydantic_util import data_to_pydantic_model, schema_to_pydantic_model

# Create model from data dictionary
data = {"name": "Alice", "age": 30, "address": {"city": "NYC", "zip": "10001"}}
UserModel = data_to_pydantic_model(data, "User")

# Create model from JSON schema
schema = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "price": {"type": "number"}
    }
}
ProductModel = schema_to_pydantic_model(schema)

Model Validation and Selection

Check data validity and find matching models:

from ju.pydantic_util import is_valid_wrt_model, valid_models

# Check if data is valid for a specific model
is_valid = is_valid_wrt_model({"name": "Bob", "age": 25}, UserModel)

# Find all models that validate given data
AdminModel = data_to_pydantic_model({"name": "Root", "age": 40, "is_admin": True}, "Admin")
models = [UserModel, ProductModel, AdminModel]
matching = list(valid_models(data, models))

Code Generation with Transformations

Convert models and schemas to Python code with optional transformations:

from ju.pydantic_util import pydantic_model_to_code

# Generate code from model
code = pydantic_model_to_code(UserModel)

# Apply transformations during generation
def fix_field_names(schema):
    # Transform problematic field names
    if 'properties' in schema:
        for old_name, new_name in [('class_', 'class_name'), ('type_', 'type_name')]:
            if old_name in schema['properties']:
                schema['properties'][new_name] = schema['properties'].pop(old_name)
    return schema

source_schema = schema  # the JSON schema defined above
code = pydantic_model_to_code(
    source_schema, 
    ingress_transform=fix_field_names,
    egress_transform=lambda code: f"# Auto-generated\n{code}"
)

Model Introspection and Data Extraction

Extract structured information about models and use them as data extraction templates:

from ju.pydantic_util import (
    field_paths_and_annotations, 
    model_field_descriptions,
    ModelExtractor
)

# Get flattened field paths and types
paths = field_paths_and_annotations(UserModel)
# {'name': str, 'age': int, 'address.city': str, 'address.zip': str}

# Extract field descriptions
descriptions = model_field_descriptions(UserModel)

# Use models as data extraction templates
json_data = data  # the dict defined above
extractor = ModelExtractor([UserModel, AdminModel])
data_reader = extractor(json_data)  # Returns mapping with model-based paths
values = data_reader['address.city']  # Extract nested values easily

The module handles complex scenarios like nested models, generic types, collections, and provides flexible validation and transformation capabilities.

Metadata

Release files for ju 0.1.45

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ju 0.1.45
File Size Uploaded Provenance Actions
ju-0.1.45.tar.gz 58.4 kB Without provenance Details for ju-0.1.45.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ju 0.1.45
File Interpreter ABI Platform Actions
ju-0.1.45-py3-none-any.whl Python 3 none any Details for ju-0.1.45-py3-none-any.whl

Total release size: 123.1 kB

Release files / ju-0.1.45.tar.gz

Download URL ju-0.1.45.tar.gz
Size 58.4 kB
Tags Source
SHA-256 checksum
How to use checksums
979547491e4e46f0d54c03be37eb45c336704d48701304d359d3332ab6a9355c
BLAKE2b-256 checksum
How to use checksums
70339e1791bd1d7e24e783ae3f9d658e5e0a6aa1da15a430a407603f8084ecc7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / ju-0.1.45-py3-none-any.whl

Download URL ju-0.1.45-py3-none-any.whl
Size 64.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
38186508e612c9209aa1ae1d142aae5899f4d48b46327a52db0b022bddd52a5b
BLAKE2b-256 checksum
How to use checksums
a2bd135ccf39daf6d97719185a85fe84682035ead3c9750019b350cec36f5922
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for ju 0.1.45

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.45 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page