Easily serialize dataclasses to and from JSON.
npx @tessl/cli install tessl/pypi-dataclasses-json@0.6.0A simple API for encoding and decoding Python dataclasses to and from JSON. This library integrates seamlessly with Python's built-in dataclasses module to provide automatic JSON serialization/deserialization with support for custom field configurations, letter case conversion, schema validation, and flexible handling of undefined parameters.
pip install dataclasses-jsonfrom dataclasses_json import dataclass_json, DataClassJsonMixin
from dataclasses_json import LetterCase, config, Undefined, CatchAll, Exclude
from dataclasses_json import global_config, UndefinedParameterErrorfrom dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class Person:
name: str
age: int
# Serialization
person = Person("Alice", 30)
json_str = person.to_json() # '{"name": "Alice", "age": 30}'
dict_data = person.to_dict() # {'name': 'Alice', 'age': 30}
# Deserialization
person2 = Person.from_json('{"name": "Bob", "age": 25}')
person3 = Person.from_dict({'name': 'Charlie', 'age': 35})
# Schema validation
schema = Person.schema()
validated_person = schema.loads('{"name": "David", "age": 40}')The library provides two main integration approaches:
@dataclass_json decorator adds methods to existing dataclassesDataClassJsonMixin base class provides the same functionality through inheritanceBoth approaches add identical methods (to_json, from_json, to_dict, from_dict, schema) and support the same configuration options. The core functionality leverages marshmallow for schema generation and validation, while maintaining simplicity for common use cases.
Fundamental JSON serialization and deserialization functionality for dataclasses, including conversion to/from JSON strings and dictionaries, plus marshmallow schema generation for validation.
# Decorator approach
def dataclass_json(
_cls: Optional[Type[T]] = None,
*,
letter_case: Optional[LetterCase] = None,
undefined: Optional[Union[str, Undefined]] = None
) -> Union[Callable[[Type[T]], Type[T]], Type[T]]: ...
# Mixin class
class DataClassJsonMixin:
dataclass_json_config: Optional[dict]
def to_json(self, **kwargs) -> str: ...
def to_dict(self, encode_json: bool = False) -> Dict[str, Json]: ...
@classmethod
def from_json(cls: Type[A], s: JsonData, *, infer_missing: bool = False, **kwargs) -> A: ...
@classmethod
def from_dict(cls: Type[A], kvs: Json, *, infer_missing: bool = False) -> A: ...
@classmethod
def schema(cls: Type[A], *, infer_missing: bool = False, **kwargs) -> "SchemaType[A]": ...Fine-grained control over field-level serialization behavior, including custom encoders/decoders, field naming, exclusion rules, and marshmallow field integration.
def config(
metadata: Optional[dict] = None,
*,
encoder: Optional[Callable] = None,
decoder: Optional[Callable] = None,
mm_field: Optional[Field] = None,
letter_case: Optional[Union[Callable[[str], str], LetterCase]] = None,
undefined: Optional[Union[str, Undefined]] = None,
field_name: Optional[str] = None,
exclude: Optional[Callable] = None
) -> Dict[str, dict]: ...
class LetterCase(Enum):
CAMEL = ... # camelCase
KEBAB = ... # kebab-case
SNAKE = ... # snake_case
PASCAL = ... # PascalCase
class Exclude:
ALWAYS: Callable[[object], bool]
NEVER: Callable[[object], bool]Strategies for handling JSON fields that don't correspond to dataclass fields, including raising exceptions, ignoring extra fields, or capturing them in a catch-all field.
class Undefined(Enum):
INCLUDE = ... # Store in CatchAll field
RAISE = ... # Raise UndefinedParameterError
EXCLUDE = ... # Ignore undefined parameters
CatchAll = Optional[CatchAllVar] # CatchAllVar bound to Mapping
class UndefinedParameterError(Exception): ...Package-wide settings for custom encoders, decoders, and marshmallow fields that apply across all dataclasses unless overridden at the field level.
class _GlobalConfig:
encoders: Dict[Union[type, Optional[type]], Callable]
decoders: Dict[Union[type, Optional[type]], Callable]
mm_fields: Dict[Union[type, Optional[type]], Field]
global_config: _GlobalConfig# Core JSON-compatible types
Json = Union[dict, list, str, int, float, bool, None]
# Input types for JSON deserialization
JsonData = Union[str, bytes, bytearray]
# Type variables for generic methods
A = TypeVar('A', bound="DataClassJsonMixin")
T = TypeVar('T')
# CatchAll type for undefined parameter handling
CatchAllVar = TypeVar("CatchAllVar", bound=Mapping)In addition to standard JSON types (str, int, float, bool, None, list, dict), the library supports:
The library provides comprehensive error handling through several exception types:
# Validation errors from marshmallow
class ValidationError(Exception):
"""Raised when schema validation fails during deserialization."""
# Undefined parameter handling errors
class UndefinedParameterError(ValidationError):
"""Raised when undefined parameters are encountered with RAISE strategy."""Common Error Scenarios:
Undefined.RAISE strategyfrom_json() calls