Registry / serialization / jsonschema-pydantic

jsonschema-pydantic

JSON →
library0.6pypypi✓ verified 85d ago

jsonschema-pydantic is a Python library that programmatically converts JSON Schemas into Pydantic models, enabling strong data validation and serialization based on schema definitions. Currently at version 0.6, it is actively developed with frequent minor releases to enhance schema feature support and Pydantic version compatibility.

pip install jsonschema-pydantic
INSTALL
IMPORT
SIG · JSONSCHEMA-PYDANTI
J
jsonschema-pydantic
serializationpythonv0.6
Install
3.3s avg
Import
500ms
Disk
26MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.522s · 27.9MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.3s · import 0.479s · 27MB
26MB installed
● package 26MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

jsonschema_to_pydantic
from jsonschema_pydantic import jsonschema_to_pydantic

Demonstrates how to define a JSON Schema, convert it into a Pydantic model using `jsonschema_to_pydantic`, and then use the generated model for data validation and instantiation. This example also shows how schema properties like 'description' and 'minimum' are translated to Pydantic model fields and validations.

from jsonschema_pydantic import jsonschema_to_pydantic json_schema = { "type": "object", "properties": { "name": {"type": "string", "description": "The name of the user"}, "age": {"type": "integer", "minimum": 0}, "email": {"type": "string", "format": "email"} }, "required": ["name", "age"] } # Convert the JSON Schema to a Pydantic model UserModel = jsonschema_to_pydantic(json_schema, model_name='User') # Instantiate and validate the generated model try: user_data = UserModel(name="Alice", age=30, email="alice@example.com") print(f"Successfully created user: {user_data.model_dump_json(indent=2)}") # Example of validation error invalid_user_data = UserModel(name="Bob", age=-5) # age < minimum except Exception as e: print(f"Validation error: {e}")
Debug
Known issues
breakingPydantic V1 vs V2 Compatibility: While jsonschema-pydantic v0.5.0 introduced backward compatibility for Pydantic V1, Pydantic V2 itself has significant breaking changes. Ensure the Pydantic version installed in your environment matches the expected version for your generated models to avoid runtime issues.
fix
Upgrade jsonschema-pydantic to v0.5.0+ and ensure your Pydantic installation (v1 or v2) aligns with your project's requirements. Review Pydantic's official migration guide if transitioning from Pydantic V1 to V2.
affects: <0.5.0
gotchaJSON Schema 'null' type conversion to Python 'None': As of v0.4.0, the library converts 'null' type in JSON Schema properties to Python's `None` type annotation. Older versions might have handled this differently, potentially leading to discrepancies if relying on specific default behaviors.
fix
Update to jsonschema-pydantic v0.4.0 or newer. Explicitly define defaults in your JSON schema for nullable fields if precise behavior is required, e.g., `{'type': ['string', 'null'], 'default': None}`.
affects: <0.4.0
gotchaSchema and Field Descriptions/Titles: Version 0.6.0 improved the incorporation of JSON schema and field descriptions into the generated Pydantic models. For older versions, detailed descriptions or titles might have been ignored, impacting documentation or schema generation fidelity.
fix
Upgrade to jsonschema-pydantic v0.6.0+ to ensure `description` and `title` fields from your JSON schema are properly reflected in the generated Pydantic models.
affects: <0.6.0
Errors
Common errors & fixes
pydantic.errors.PydanticUserError: Field ... has `init=False` and dataclass has config setting `extra="allow"`. This combination is not allowed.
This error typically arises in Pydantic V2 when a Pydantic dataclass (or a BaseModel behaving like one) is configured to allow extra fields but also has fields set with `init=False`. This is a Pydantic-level restriction, which can surface if the `jsonschema-pydantic` generated model's configuration implicitly creates this conflict.
fix
Review the JSON schema definition for properties that might lead to `init=False` (e.g., complex default factories or computed fields) in conjunction with any `extra_properties` or `additionalProperties` settings in the schema. Adjust the JSON schema or manually modify the generated Pydantic model (if applicable) to remove this conflict.
pydantic.errors.PydanticUndefinedAnnotation: Name '...' is not defined
This error indicates that a type annotation within the generated Pydantic model could not be resolved. This often occurs with circular references in the JSON schema or when a type is referenced before it's fully defined, particularly in complex nested schemas or self-referential structures.
fix
For complex nested or circular schemas, Pydantic might require explicit forward references or a `model_rebuild()` call. While `jsonschema-pydantic` handles common cases, for very intricate schemas, you might need to simplify the JSON schema or manually adjust the generated model to include `from typing import ForwardRef` and `Model.model_rebuild()` after all class definitions.
pydantic.ValidationError: 1 validation error for UserModel...
The data provided for validation does not conform to the rules defined in the generated Pydantic model (and thus, the original JSON Schema). Common causes include missing required fields, incorrect data types, or values outside specified constraints (e.g., `minimum`, `maximum`).
fix
Carefully examine the `ValidationError` message, specifically the `loc` (location) and `msg` (message) fields, to identify which part of your input data violates the schema. Adjust your input data to match the expected structure and constraints defined by the JSON schema.
Upgrade
Version history
0.6latest on PyPI · released Feb 3, 2024
Audit
Dependencies
pydanticrequiredCore dependency for generated models and internal logic. The library aims for compatibility with both Pydantic v1 and v2.
Agent activity
4 hits · last 30 days
node
4
Resources
jsonschema-pydantic — pip install jsonschema-pydantic · libregistry