or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-serialization.mdfield-configuration.mdglobal-configuration.mdindex.mdundefined-parameters.md
tile.json

tessl/pypi-dataclasses-json

Easily serialize dataclasses to and from JSON.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/dataclasses-json@0.6.x

To install, run

npx @tessl/cli install tessl/pypi-dataclasses-json@0.6.0

index.mddocs/

Dataclasses JSON

A 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.

Package Information

  • Package Name: dataclasses-json
  • Language: Python
  • Installation: pip install dataclasses-json
  • Minimum Python Version: 3.7

Core Imports

from dataclasses_json import dataclass_json, DataClassJsonMixin
from dataclasses_json import LetterCase, config, Undefined, CatchAll, Exclude
from dataclasses_json import global_config, UndefinedParameterError

Basic Usage

from 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}')

Architecture

The library provides two main integration approaches:

  • Decorator approach: @dataclass_json decorator adds methods to existing dataclasses
  • Mixin approach: DataClassJsonMixin base class provides the same functionality through inheritance

Both 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.

Capabilities

Core Serialization

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]": ...

Core Serialization

Field Configuration

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]

Field Configuration

Undefined Parameter Handling

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): ...

Undefined Parameter Handling

Global Configuration

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

Global Configuration

Type Definitions

# 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)

Supported Types

In addition to standard JSON types (str, int, float, bool, None, list, dict), the library supports:

  • Nested dataclasses: Automatic recursive serialization
  • Collections: List, Set, Tuple, Dict and other Collection types
  • Optional types: Union[T, None] and Optional[T]
  • Datetime objects: Serialized as timestamps by default
  • UUID objects: Serialized as strings
  • Decimal objects: Serialized as strings
  • Enum types: Serialized using enum values
  • Custom types: Via custom encoders/decoders

Error Handling

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:

  • ValidationError: Schema validation failures, type mismatches, required field violations
  • UndefinedParameterError: Extra fields when using Undefined.RAISE strategy
  • JSONDecodeError: Invalid JSON format in from_json() calls
  • TypeError: Attempting to serialize non-serializable types without custom encoders
  • AttributeError: Missing dataclass fields or incorrect usage patterns