Dataclasses JSON
raw JSON → 0.6.7 verified Tue May 12 auth: no python install: verified quickstart: verified
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.
pip install dataclasses-json Common errors
error KeyError: 'field_name' ↓
cause 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). error marshmallow.exceptions.ValidationError: {'field_name': ['Invalid type.']}` or `marshmallow.exceptions.ValidationError: {'field_name': ['Missing data for required field.']} ↓
cause 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). error AttributeError: type object 'tuple' has no attribute '__args__' ↓
cause 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). error TypeError: __init__() got an unexpected keyword argument 'X' ↓
cause 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:
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class MyDataClass:
field_a: str
field_b: int Warnings
breaking Union 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.
gotcha Version 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.
gotcha When 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.
gotcha Generic 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.
gotcha Overriding 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.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.20s 19.4M
3.10 slim (glibc) - - 0.14s 20M
3.11 alpine (musl) - - 0.31s 21.5M
3.11 slim (glibc) - - 0.26s 22M
3.12 alpine (musl) - - 0.26s 13.3M
3.12 slim (glibc) - - 0.26s 14M
3.13 alpine (musl) - - 0.20s 12.9M
3.13 slim (glibc) - - 0.21s 13M
3.9 alpine (musl) - - 0.17s 18.9M
3.9 slim (glibc) - - 0.14s 19M
Imports
- dataclass_json
from dataclasses_json import dataclass_json - DataClassJsonMixin
from dataclasses_json import DataClassJsonMixin - LetterCase
from dataclasses_json import LetterCase
Quickstart verified last tested: 2026-04-23
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}")