Dataclasses JSON
Dataclasses-json provides a simple API for encoding and decoding Python dataclasses to and from JSON. It extends Python's built-in `dataclasses` module with automatic JSON serialization and deserialization capabilities, supporting features like custom field configurations, letter case conversion, schema validation, and flexible handling of undefined parameters. The library is actively maintained with frequent minor releases, with the current stable version being 0.6.7.
Warnings
- gotcha The `@dataclass_json` decorator must be placed *above* the built-in `@dataclass` decorator. Incorrect ordering can lead to unexpected behavior or errors.
- gotcha Deserialization of `Union` types can be complex. If not explicitly tagged (e.g., with a `__type` field) or if multiple types in the Union can match the input JSON, `dataclasses-json` might deserialize to a generic `dict` instead of the intended dataclass, or fail to correctly infer the type. This is especially true for 'naive' unions without explicit discriminators.
- gotcha Using `from __future__ import annotations` can interfere with `dataclasses-json`'s ability to access type annotations, potentially causing serialization or deserialization issues.
- gotcha Naive `datetime` objects are encoded as `float` (UNIX timestamps) and decoded into timezone-aware `datetime` objects (using the system's local timezone). This can lead to non-inverse transformations for naive datetimes.
- gotcha When deserializing JSON with fields not present in the dataclass (undefined parameters), the default behavior may vary or result in `KeyError` or `ValidationError`. The `undefined` parameter (e.g., `Undefined.RAISE`, `Undefined.EXCLUDE`, `Undefined.INCLUDE`) on `dataclass_json` or per-field `config` dictates this behavior.
- deprecated Python 3.7 support is still present but may be removed in future minor releases after 0.6.0. Python 3.7 is end-of-life and no longer receives official support.
Install
-
pip install dataclasses-json
Imports
- dataclass_json
from dataclasses_json import dataclass_json
- DataClassJsonMixin
from dataclasses_json import DataClassJsonMixin
Quickstart
from dataclasses import dataclass
from dataclasses_json import dataclass_json
import json
@dataclass_json
@dataclass
class Person:
name: str
age: int
city: str
# Encoding to JSON
person_instance = Person(name='Alice', age=30, city='New York')
json_string = person_instance.to_json(indent=2)
print(f"Serialized JSON:\n{json_string}")
# Decoding from JSON
raw_json = '{"name": "Bob", "age": 25, "city": "London"}'
decoded_person = Person.from_json(raw_json)
print(f"Deserialized Person: {decoded_person}")