Skip to content

JSON Schema API Reference

Auto-generated API documentation for the jsonschema module.

jsonschema

JSON Schema flattening & sanitization — zero dependencies, stdlib only.

Flatten complex JSON Schemas containing $ref, allOf, anyOf, and oneOf into simple, LLM-provider-compatible schemas. Designed for tool schemas consumed by Anthropic, OpenAI, and Google GenAI APIs.

Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.

Example::

>>> from jsonschema import flatten_schema
>>> schema = {
...     "type": "object",
...     "properties": {
...         "user": {"$ref": "#/$defs/User"},
...     },
...     "$defs": {
...         "User": {
...             "type": "object",
...             "properties": {"name": {"type": "string"}},
...         }
...     },
... }
>>> flatten_schema(schema)
{'type': 'object', 'properties': {'user': {'type': 'object', 'properties': {'name': {'type': 'string'}}}}}

Pipeline::

resolve_refs  →  merge_allof  →  simplify_unions  →  sanitize

resolve_refs(schema)

Resolve all local $ref pointers and inline their targets.

Supports any JSON Pointer fragment (RFC 6901), including #/$defs/, #/definitions/, #/components/schemas/, etc. After resolution, $defs and definitions maps are removed.

Parameters:

Name Type Description Default
schema dict[str, Any]

A JSON Schema dict.

required

Returns:

Type Description
dict[str, Any]

A new dict with all $ref inlined and definition maps removed.

Source code in jsonschema/jsonschema.py
def resolve_refs(schema: dict[str, Any]) -> dict[str, Any]:
    """Resolve all local ``$ref`` pointers and inline their targets.

    Supports any JSON Pointer fragment (RFC 6901), including
    ``#/$defs/``, ``#/definitions/``, ``#/components/schemas/``, etc.
    After resolution, ``$defs`` and ``definitions`` maps are removed.

    Args:
        schema: A JSON Schema dict.

    Returns:
        A new dict with all ``$ref`` inlined and definition maps removed.
    """
    schema = copy.deepcopy(schema)
    result = _inline_refs(schema, schema)
    # Strip consumed definition maps.
    for key in _DEFS_KEYS:
        result.pop(key, None)
    return result

merge_allof(schema)

Deep-merge all allOf sub-schemas into single schemas.

Parameters:

Name Type Description Default
schema dict[str, Any]

A JSON Schema dict ($ref should be resolved first).

required

Returns:

Type Description
dict[str, Any]

A new dict with all allOf keywords resolved.

Source code in jsonschema/jsonschema.py
def merge_allof(schema: dict[str, Any]) -> dict[str, Any]:
    """Deep-merge all ``allOf`` sub-schemas into single schemas.

    Args:
        schema: A JSON Schema dict (``$ref`` should be resolved first).

    Returns:
        A new dict with all ``allOf`` keywords resolved.
    """
    return _walk_merge_allof(copy.deepcopy(schema))

simplify_unions(schema)

Simplify anyOf/oneOf constructs.

  • Nullable pattern [{type: T}, {type: null}]{type: T, nullable: true}
  • Single-variant: unwrap.
  • Multi-variant: keep first non-null variant (lossy but safe for LLM tool schemas).

Parameters:

Name Type Description Default
schema dict[str, Any]

A JSON Schema dict.

required

Returns:

Type Description
dict[str, Any]

A new dict with anyOf/oneOf simplified.

Source code in jsonschema/jsonschema.py
def simplify_unions(schema: dict[str, Any]) -> dict[str, Any]:
    """Simplify ``anyOf``/``oneOf`` constructs.

    - Nullable pattern ``[{type: T}, {type: null}]`` → ``{type: T, nullable: true}``
    - Single-variant: unwrap.
    - Multi-variant: keep first non-null variant (lossy but safe for LLM tool
      schemas).

    Args:
        schema: A JSON Schema dict.

    Returns:
        A new dict with ``anyOf``/``oneOf`` simplified.
    """
    return _walk_simplify(copy.deepcopy(schema))

sanitize(schema, *, strip_keys=None)

Strip unsupported schema keywords and validate required arrays.

Parameters:

Name Type Description Default
schema dict[str, Any]

A JSON Schema dict.

required
strip_keys set[str] | None

Additional keys to strip beyond :data:UNSUPPORTED_SCHEMA_KEYS.

None

Returns:

Type Description
dict[str, Any]

A new dict with unsupported keys removed and required arrays

dict[str, Any]

pruned so that required ⊆ properties.keys() at every level.

Source code in jsonschema/jsonschema.py
def sanitize(
    schema: dict[str, Any],
    *,
    strip_keys: set[str] | None = None,
) -> dict[str, Any]:
    """Strip unsupported schema keywords and validate ``required`` arrays.

    Args:
        schema: A JSON Schema dict.
        strip_keys: Additional keys to strip beyond
            :data:`UNSUPPORTED_SCHEMA_KEYS`.

    Returns:
        A new dict with unsupported keys removed and ``required`` arrays
        pruned so that ``required ⊆ properties.keys()`` at every level.
    """
    strip = UNSUPPORTED_SCHEMA_KEYS | (strip_keys or set())
    return _walk_sanitize(copy.deepcopy(schema), strip)

flatten_schema(schema, *, strip_keys=None)

One-call full pipeline: resolve → merge → simplify → sanitize.

Parameters:

Name Type Description Default
schema dict[str, Any]

A JSON Schema dict, possibly containing $ref, allOf, anyOf, oneOf, and unsupported keywords.

required
strip_keys set[str] | None

Additional keys to strip beyond :data:UNSUPPORTED_SCHEMA_KEYS.

None

Returns:

Type Description
dict[str, Any]

A flattened, sanitized schema safe for LLM provider consumption.

Source code in jsonschema/jsonschema.py
def flatten_schema(
    schema: dict[str, Any],
    *,
    strip_keys: set[str] | None = None,
) -> dict[str, Any]:
    """One-call full pipeline: resolve → merge → simplify → sanitize.

    Args:
        schema: A JSON Schema dict, possibly containing ``$ref``,
            ``allOf``, ``anyOf``, ``oneOf``, and unsupported keywords.
        strip_keys: Additional keys to strip beyond
            :data:`UNSUPPORTED_SCHEMA_KEYS`.

    Returns:
        A flattened, sanitized schema safe for LLM provider consumption.
    """
    result = resolve_refs(schema)
    result = _walk_merge_allof(result)  # skip redundant deepcopy
    result = _walk_simplify(result)
    strip = UNSUPPORTED_SCHEMA_KEYS | (strip_keys or set())
    result = _walk_sanitize(result, strip)
    return result