json_schema_to_base_model(
schema: dict[str, Any], model_cls: type[TModel] = BaseModel
) -> type[TModel]
Create a pydantic model from a JSON schema object.
Handles nested objects and arrays, enum (an Enum for strings, Literal
otherwise), anyOf / oneOf and "type": [...] (unions, "null" is None),
and $refs into $defs / definitions (also recursive ones).
Source code in src/schemez/schema_to_type/simple_impl.py
| def json_schema_to_base_model[TModel: BaseModel = BaseModel](
schema: dict[str, Any],
model_cls: type[TModel] = BaseModel, # ty: ignore[invalid-parameter-default]
) -> type[TModel]:
"""Create a pydantic model from a JSON schema object.
Handles nested objects and arrays, `enum` (an Enum for strings, `Literal`
otherwise), `anyOf` / `oneOf` and `"type": [...]` (unions, `"null"` is None),
and `$ref`s into `$defs` / `definitions` (also recursive ones).
"""
builder = _ModelBuilder(schema)
model = builder.build(schema, schema.get("title", "DynamicModel"), model_cls)
for created in builder.created:
created.model_rebuild(_types_namespace=builder.namespace)
return model
|