Easily serialize dataclasses to and from JSON.
npx @tessl/cli install tessl/pypi-dataclasses-json@0.6.00
# Dataclasses JSON
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: dataclasses-json
7
- **Language**: Python
8
- **Installation**: `pip install dataclasses-json`
9
- **Minimum Python Version**: 3.7
10
11
## Core Imports
12
13
```python
14
from dataclasses_json import dataclass_json, DataClassJsonMixin
15
from dataclasses_json import LetterCase, config, Undefined, CatchAll, Exclude
16
from dataclasses_json import global_config, UndefinedParameterError
17
```
18
19
## Basic Usage
20
21
```python
22
from dataclasses import dataclass
23
from dataclasses_json import dataclass_json
24
25
@dataclass_json
26
@dataclass
27
class Person:
28
name: str
29
age: int
30
31
# Serialization
32
person = Person("Alice", 30)
33
json_str = person.to_json() # '{"name": "Alice", "age": 30}'
34
dict_data = person.to_dict() # {'name': 'Alice', 'age': 30}
35
36
# Deserialization
37
person2 = Person.from_json('{"name": "Bob", "age": 25}')
38
person3 = Person.from_dict({'name': 'Charlie', 'age': 35})
39
40
# Schema validation
41
schema = Person.schema()
42
validated_person = schema.loads('{"name": "David", "age": 40}')
43
```
44
45
## Architecture
46
47
The library provides two main integration approaches:
48
49
- **Decorator approach**: `@dataclass_json` decorator adds methods to existing dataclasses
50
- **Mixin approach**: `DataClassJsonMixin` base class provides the same functionality through inheritance
51
52
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.
53
54
## Capabilities
55
56
### Core Serialization
57
58
Fundamental JSON serialization and deserialization functionality for dataclasses, including conversion to/from JSON strings and dictionaries, plus marshmallow schema generation for validation.
59
60
```python { .api }
61
# Decorator approach
62
def dataclass_json(
63
_cls: Optional[Type[T]] = None,
64
*,
65
letter_case: Optional[LetterCase] = None,
66
undefined: Optional[Union[str, Undefined]] = None
67
) -> Union[Callable[[Type[T]], Type[T]], Type[T]]: ...
68
69
# Mixin class
70
class DataClassJsonMixin:
71
dataclass_json_config: Optional[dict]
72
73
def to_json(self, **kwargs) -> str: ...
74
def to_dict(self, encode_json: bool = False) -> Dict[str, Json]: ...
75
76
@classmethod
77
def from_json(cls: Type[A], s: JsonData, *, infer_missing: bool = False, **kwargs) -> A: ...
78
@classmethod
79
def from_dict(cls: Type[A], kvs: Json, *, infer_missing: bool = False) -> A: ...
80
@classmethod
81
def schema(cls: Type[A], *, infer_missing: bool = False, **kwargs) -> "SchemaType[A]": ...
82
```
83
84
[Core Serialization](./core-serialization.md)
85
86
### Field Configuration
87
88
Fine-grained control over field-level serialization behavior, including custom encoders/decoders, field naming, exclusion rules, and marshmallow field integration.
89
90
```python { .api }
91
def config(
92
metadata: Optional[dict] = None,
93
*,
94
encoder: Optional[Callable] = None,
95
decoder: Optional[Callable] = None,
96
mm_field: Optional[Field] = None,
97
letter_case: Optional[Union[Callable[[str], str], LetterCase]] = None,
98
undefined: Optional[Union[str, Undefined]] = None,
99
field_name: Optional[str] = None,
100
exclude: Optional[Callable] = None
101
) -> Dict[str, dict]: ...
102
103
class LetterCase(Enum):
104
CAMEL = ... # camelCase
105
KEBAB = ... # kebab-case
106
SNAKE = ... # snake_case
107
PASCAL = ... # PascalCase
108
109
class Exclude:
110
ALWAYS: Callable[[object], bool]
111
NEVER: Callable[[object], bool]
112
```
113
114
[Field Configuration](./field-configuration.md)
115
116
### Undefined Parameter Handling
117
118
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.
119
120
```python { .api }
121
class Undefined(Enum):
122
INCLUDE = ... # Store in CatchAll field
123
RAISE = ... # Raise UndefinedParameterError
124
EXCLUDE = ... # Ignore undefined parameters
125
126
CatchAll = Optional[CatchAllVar] # CatchAllVar bound to Mapping
127
128
class UndefinedParameterError(Exception): ...
129
```
130
131
[Undefined Parameter Handling](./undefined-parameters.md)
132
133
### Global Configuration
134
135
Package-wide settings for custom encoders, decoders, and marshmallow fields that apply across all dataclasses unless overridden at the field level.
136
137
```python { .api }
138
class _GlobalConfig:
139
encoders: Dict[Union[type, Optional[type]], Callable]
140
decoders: Dict[Union[type, Optional[type]], Callable]
141
mm_fields: Dict[Union[type, Optional[type]], Field]
142
143
global_config: _GlobalConfig
144
```
145
146
[Global Configuration](./global-configuration.md)
147
148
## Type Definitions
149
150
```python { .api }
151
# Core JSON-compatible types
152
Json = Union[dict, list, str, int, float, bool, None]
153
154
# Input types for JSON deserialization
155
JsonData = Union[str, bytes, bytearray]
156
157
# Type variables for generic methods
158
A = TypeVar('A', bound="DataClassJsonMixin")
159
T = TypeVar('T')
160
161
# CatchAll type for undefined parameter handling
162
CatchAllVar = TypeVar("CatchAllVar", bound=Mapping)
163
```
164
165
## Supported Types
166
167
In addition to standard JSON types (str, int, float, bool, None, list, dict), the library supports:
168
169
- **Nested dataclasses**: Automatic recursive serialization
170
- **Collections**: List, Set, Tuple, Dict and other Collection types
171
- **Optional types**: Union[T, None] and Optional[T]
172
- **Datetime objects**: Serialized as timestamps by default
173
- **UUID objects**: Serialized as strings
174
- **Decimal objects**: Serialized as strings
175
- **Enum types**: Serialized using enum values
176
- **Custom types**: Via custom encoders/decoders
177
178
## Error Handling
179
180
The library provides comprehensive error handling through several exception types:
181
182
```python { .api }
183
# Validation errors from marshmallow
184
class ValidationError(Exception):
185
"""Raised when schema validation fails during deserialization."""
186
187
# Undefined parameter handling errors
188
class UndefinedParameterError(ValidationError):
189
"""Raised when undefined parameters are encountered with RAISE strategy."""
190
```
191
192
**Common Error Scenarios:**
193
194
- **ValidationError**: Schema validation failures, type mismatches, required field violations
195
- **UndefinedParameterError**: Extra fields when using `Undefined.RAISE` strategy
196
- **JSONDecodeError**: Invalid JSON format in `from_json()` calls
197
- **TypeError**: Attempting to serialize non-serializable types without custom encoders
198
- **AttributeError**: Missing dataclass fields or incorrect usage patterns