Registry / serialization / dataclasses-jsonschema

dataclasses-jsonschema

JSON →
library2.16.0pypypi✓ verified 86d ago

The `dataclasses-jsonschema` library (current version 2.16.0) provides a straightforward way to generate JSON schemas from Python dataclasses. It augments dataclasses with a `JsonSchemaMixin` to expose schema generation capabilities and includes utilities for type conversion. The library maintains an active release cadence, frequently addressing bug fixes, improving type handling, and adding support for newer Python features.

pip install dataclasses-jsonschema
INSTALL
IMPORT
SIG · DATACLASSES-JSONSC
D
dataclasses-jsonschema
serializationpythonv2.16.0
Install
2.6s avg
Import
274ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.16.0 · 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.910 runs
installs and imports cleanly · install 0.0s · import 0.286s · 22.5MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.6s · import 0.262s · 23MB
21MB installed
● package 21MB
Code
Verified usage

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

JsonSchemaMixin
from dataclasses_jsonschema import JsonSchemaMixin
dataclass
from dataclasses import dataclass
Remember to import `dataclass` from the standard `dataclasses` module.

Define a dataclass that inherits from `JsonSchemaMixin`. Then, call the static method `.json_schema()` on the dataclass to retrieve the generated JSON schema. This example demonstrates basic field types and metadata usage.

from dataclasses import dataclass, field from datetime import datetime from dataclasses_jsonschema import JsonSchemaMixin @dataclass class Person(JsonSchemaMixin): name: str age: int = field(metadata=dict(description="Age in years")) birth_date: datetime # Example with an optional field email: str | None = None # Use typing.Optional for Python < 3.10 # Generate the JSON schema schema = Person.json_schema() # Print the generated schema import json print(json.dumps(schema, indent=2))
Debug
Known issues
gotchaWhen using built-in generic types (e.g., `list[str]`, `dict[str, int]`) in Python versions older than 3.9, you must include `from __future__ import annotations` at the top of your module.
fix
Add `from __future__ import annotations` or use `typing.List[str]` for older Python versions.
affects: < 2.14.0 (Python < 3.9)
breakingSupport for PEP 585 (built-in generics like `list[str]`) and PEP 604 (union operator `|`) was introduced in version 2.14.0. If you upgrade to 2.14.0+ and start using these new syntaxes without `from __future__ import annotations` on Python < 3.9, your code might break.
fix
Ensure `from __future__ import annotations` is present, or stick to `typing.List`/`typing.Union` for compatibility.
affects: >= 2.14.0 (on Python < 3.9)
gotcha`dataclasses-jsonschema` is specifically designed for JSON schema generation from dataclasses. It does not provide runtime data validation, parsing, or serialization/deserialization like libraries such as Pydantic do. Trying to use it as a full-fledged data validation library will lead to unexpected behavior.
fix
Understand its scope: schema generation. For validation, use a dedicated library like `jsonschema` or `Pydantic`.
affects: All versions
gotchaPrior to version 2.15.0, handling of complex `Union` types, especially with `Optional` (e.g., `Optional[Union[A, B]]`), could lead to incorrect or incomplete schema generation. This was further refined in 2.15.2 and 2.15.3.
fix
Upgrade to version 2.15.3 or newer for robust handling of complex `Union` and `Optional` types.
affects: < 2.15.3
breakingDiscriminator support, crucial for OpenAPI 3.0 polymorphic schemas, was added in version 2.15.0. Any attempts to use discriminator functionality with versions older than 2.15.0 will not work as expected.
fix
Upgrade to version 2.15.0 or newer to use discriminators for OpenAPI 3.0 polymorphism.
affects: < 2.15.0
Errors
Common errors & fixes
TypeError: 'type' object is not subscriptable
Using PEP 585 type hints (e.g., `list[str]`, `dict[str, int]`) without `from __future__ import annotations` on Python 3.8 or earlier.
fix
Add `from __future__ import annotations` at the top of your file, or use `typing.List[str]` and `typing.Dict[str, int]` instead.
AttributeError: type object 'MyDataclass' has no attribute 'json_schema'
The dataclass was not correctly inherited from `dataclasses_jsonschema.JsonSchemaMixin`.
fix
Ensure your dataclass definition includes `(JsonSchemaMixin)`: `@dataclass
class MyDataclass(JsonSchemaMixin):`
jsonschema.exceptions.ValidationError: 'None' is not of type 'string'
Schema generated for an `Optional[str]` field (or similar nullable type) might not correctly mark it as nullable, especially on older `dataclasses-jsonschema` versions or with complex `Union` types.
fix
Upgrade `dataclasses-jsonschema` to the latest version (2.15.3+) to improve `Union` and `Optional` handling. Ensure your dataclass field is correctly typed as `str | None` (Python 3.10+) or `Optional[str]` (Python < 3.10).
Upgrade
Version history
2.16.0latest on PyPI · released Oct 27, 2022
Audit
Dependencies
fastuuidoptionalProvides faster UUID and datetime parsing for schema generation.
Agent activity
31 hits · last 30 days
node
30
OpenAI (training)
1
Resources
dataclasses-jsonschema — pip install dataclasses-jsonschema · libregistry