Registry / serialization / dataclasses-json

dataclasses-json

JSON →
library0.6.7pypypi✓ verified 52d ago

Dataclasses JSON is a Python library that provides a simple API for easily serializing dataclasses to and from JSON. It leverages the built-in `dataclasses` module and internally uses `marshmallow` for robust schema generation and deserialization, supporting complex types like nested dataclasses and various collections. The current version is 0.6.7, and it maintains an active release cadence with frequent bug fixes and feature enhancements.

serializationdata
pip install dataclasses-json
Install & Compatibility
Where this runs
tested against v0.6.7 · 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.925 runs
installs and imports cleanly · install 0.0s · import 0.224s · 19.6MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 2.0s · import 0.197s · 20MB
18MB installed
● package 18MB
Code
Verified usage

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

dataclass_json
from dataclasses_json import dataclass_json
DataClassJsonMixin
from dataclasses_json import DataClassJsonMixin
LetterCase
from dataclasses_json import LetterCase

This quickstart demonstrates the core functionality of `dataclasses-json` using the `@dataclass_json` decorator. It shows how to serialize dataclass instances to JSON strings and deserialize JSON strings back into dataclass instances. An example of converting field names to camelCase for JSON representation is also included.

from dataclasses import dataclass from dataclasses_json import dataclass_json, LetterCase @dataclass_json @dataclass class Person: name: str age: int @dataclass_json(letter_case=LetterCase.CAMEL) @dataclass class Product: product_id: str item_name: str # Basic usage person = Person(name='Alice', age=30) print(f"To JSON: {person.to_json()}") loaded_person = Person.from_json('{"name": "Bob", "age": 25}') print(f"From JSON: {loaded_person}") # With camelCase conversion product = Product(product_id='P123', item_name='Laptop') print(f"Product to JSON (camelCase): {product.to_json()}") loaded_product = Product.from_json('{"productId": "P456", "itemName": "Mouse"}') print(f"Product from JSON (camelCase): {loaded_product}")
Debug
Known issues
breakingUnion type deserialization behavior changed significantly in v0.6.0. Earlier versions (pre-0.6.0) often struggled with correctly deserializing complex Union types, especially when nested within lists or dictionaries, or when a discriminating field was not present. v0.6.0 introduced automatic coercion of built-in types without exceptions, and subsequent versions (e.g., v0.6.1, v0.6.4) provided further fixes for Union deserialization logic.
fix
Upgrade to v0.6.0 or higher. For complex Union types, ensure your data has sufficient information for `dataclasses-json` to infer the correct type, or provide custom decoding logic.
affects: <0.6.0
gotchaVersion 0.6.7 includes a warning about 'buggy type resolution'. This can manifest as unexpected deserialization behavior or warnings during schema generation, particularly when using advanced type hints or `from __future__ import annotations`, which can sometimes interfere with how `dataclasses-json` introspects types. Earlier issues reported 'Unknown type warning' for basic types like `int` under these conditions.
fix
Review type hint usage for complexity. If encountering 'Unknown type' warnings with `from __future__ import annotations`, consider separating dataclass definitions into files without this import, or explicitly providing Marshmallow fields via `mm_field` metadata for problematic fields.
affects: >=0.6.7 and potentially earlier versions with `from __future__ import annotations`
gotchaWhen encoding/decoding `datetime` objects, `dataclasses-json` converts them to/from float timestamps. A significant caveat is that if a `datetime` object is timezone-naive during encoding, it will be assumed to be in the system's local timezone. Upon decoding, it will be converted into a timezone-aware object (also in the system's local timezone). This can lead to non-inverse behavior, where `obj.from_json(obj.to_json()) != obj` if the original object was naive.
fix
Always use timezone-aware `datetime` objects for predictable serialization/deserialization, or implement custom encoders/decoders (e.g., for ISO 8601 string format) if exact inverse behavior or specific timezone handling is required.
affects: All versions
gotchaGeneric dataclasses did not always deserialize correctly in older versions, often resulting in a dictionary instead of the intended generic dataclass instance. This was a known limitation that was addressed in v0.6.5.
fix
Upgrade to v0.6.5 or a newer version to ensure proper deserialization of generic dataclasses.
affects: <0.6.5
gotchaOverriding the `__init__` method in a dataclass that uses `@dataclass_json` can interfere with the methods automatically generated by the `@dataclass` decorator (and by extension, `dataclasses-json`). This can lead to `AttributeError` for fields that are not properly initialized within the custom `__init__`.
fix
Avoid overriding `__init__` directly. Instead, use `__post_init__` for post-initialization logic. If `__init__` must be overridden, ensure all dataclass fields are correctly initialized.
affects: All versions
Errors
Common errors & fixes
KeyError: 'field_name'
When deserializing JSON using `from_dict` or `from_json`, a required field (or an `Optional` field without a default value) is missing from the input JSON data. `dataclasses-json` attempts to access a key that does not exist in the deserialized dictionary.
fix
Provide a default value for the field in the dataclass (e.g., `field_name: Optional[str] = None`). Alternatively, if the field should genuinely be optional and infer `None` if missing, use `infer_missing=True` when calling `from_dict` or `from_json`. For example: `YourDataclass.from_json(json_string, infer_missing=True)`.
marshmallow.exceptions.ValidationError: {'field_name': ['Invalid type.']}` or `marshmallow.exceptions.ValidationError: {'field_name': ['Missing data for required field.']}
When using `YourDataclass.schema().loads(json_string)` for deserialization, the input JSON data does not conform to the expected type or structure defined in the dataclass, or a required field is missing. This happens because `dataclasses-json` leverages Marshmallow for stricter schema validation when `.schema()` methods are invoked.
fix
Ensure the types in your JSON string precisely match the type hints in your dataclass. For missing required fields, provide them in the JSON string. If a field can be optional, define it as `Optional[Type]` and either provide `null` in the JSON or ensure `infer_missing=True` is used with `from_json`/`from_dict` (though `schema().loads` will still apply Marshmallow's validation rules).
AttributeError: type object 'tuple' has no attribute '__args__'
This error occurs when a dataclass field is annotated with a generic type like `list` or `tuple` without specifying the element type (e.g., `field: tuple` instead of `field: Tuple[str, int]` or `field: tuple[str, int]` in Python 3.9+). `dataclasses-json` requires explicit type arguments for container types to correctly infer the schema for nested elements during deserialization.
fix
Always provide explicit type arguments for generic types. For example, change `field: tuple` to `field: Tuple[int, str]` or `field: tuple[int, str]` (using `from typing import Tuple` if on Python < 3.9).
TypeError: __init__() got an unexpected keyword argument 'X'
This issue often arises when the `@dataclass_json` decorator is applied after `@dataclass` (e.g., `@dataclass @dataclass_json`), or when there's an interaction with other decorators or inheritance that modifies the `__init__` method in an unexpected way. The order of decorators can be crucial, as `dataclasses-json` often needs to preprocess the class before `@dataclass` generates its `__init__`.
fix
Ensure that the `@dataclass_json` decorator is applied *first*, followed by `@dataclass`. The correct order is:
```python
from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class MyDataClass:
    field_a: str
    field_b: int
```
Upgrade
Version history
0.6.7latest on PyPI
Audit
Dependencies
dataclassesoptionalCore functionality for Python <3.7 (backport). Built-in for Python >=3.7.
marshmallowrequiredUsed internally for schema generation and advanced deserialization logic.
Agent activity
44 hits · last 30 days
ahrefsbot
3
seranking-bot
3
amazonbot
1
Resources