Easily serialize dataclasses to and from JSON.
—
Fundamental JSON serialization and deserialization functionality for dataclasses. This module provides two approaches for adding JSON capabilities to dataclasses: a decorator and a mixin class, both offering identical functionality.
The @dataclass_json decorator adds JSON methods directly to dataclass definitions, providing the most convenient integration with existing code.
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]]:
"""
Class decorator that adds JSON serialization methods to a dataclass.
Parameters:
- _cls: The dataclass to decorate (automatically provided)
- letter_case: Case conversion strategy for field names
- undefined: How to handle undefined parameters during deserialization
Returns:
The decorated class with added JSON methods
"""Usage example:
from dataclasses import dataclass
from dataclasses_json import dataclass_json, LetterCase, Undefined
@dataclass_json(letter_case=LetterCase.CAMEL, undefined=Undefined.EXCLUDE)
@dataclass
class Product:
product_name: str
unit_price: float
in_stock: bool
# This automatically adds: to_json, from_json, to_dict, from_dict, schema methodsThe DataClassJsonMixin provides the same functionality through inheritance, useful when you prefer composition over decoration.
class DataClassJsonMixin:
"""
Abstract base class providing JSON serialization methods.
Dataclasses should inherit from this class to gain JSON capabilities.
"""
dataclass_json_config: Optional[dict]
def to_json(
self,
*,
skipkeys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
indent: Optional[Union[int, str]] = None,
separators: Optional[Tuple[str, str]] = None,
default: Optional[Callable] = None,
sort_keys: bool = False,
**kw
) -> str:
"""
Serialize the dataclass instance to a JSON string.
Parameters: Same as json.dumps() plus:
- All standard json.dumps() keyword arguments are supported
Returns:
JSON string representation of the dataclass
"""
def to_dict(self, encode_json: bool = False) -> Dict[str, Json]:
"""
Convert the dataclass instance to a dictionary.
Parameters:
- encode_json: If True, encode values for JSON compatibility
Returns:
Dictionary representation of the dataclass
"""
@classmethod
def from_json(
cls: Type[A],
s: JsonData,
*,
parse_float=None,
parse_int=None,
parse_constant=None,
infer_missing: bool = False,
**kw
) -> A:
"""
Create a dataclass instance from a JSON string.
Parameters:
- s: JSON string to deserialize
- parse_float, parse_int, parse_constant: JSON parsing options
- infer_missing: Infer missing fields from defaults
- **kw: Additional json.loads() arguments
Returns:
New instance of the dataclass
"""
@classmethod
def from_dict(
cls: Type[A],
kvs: Json,
*,
infer_missing: bool = False
) -> A:
"""
Create a dataclass instance from a dictionary.
Parameters:
- kvs: Dictionary with field values
- infer_missing: Infer missing fields from defaults
Returns:
New instance of the dataclass
"""
@classmethod
def schema(
cls: Type[A],
*,
infer_missing: bool = False,
only=None,
exclude=(),
many: bool = False,
context=None,
load_only=(),
dump_only=(),
partial: bool = False,
unknown=None
) -> "SchemaType[A]":
"""
Generate a marshmallow schema for the dataclass.
Parameters:
- infer_missing: Infer missing fields from defaults
- only: Fields to include (None means all)
- exclude: Fields to exclude
- many: Handle multiple instances
- context: Schema context
- load_only: Fields for deserialization only
- dump_only: Fields for serialization only
- partial: Allow partial data
- unknown: How to handle unknown fields
Returns:
marshmallow.Schema instance for validation
"""Usage example:
from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin
@dataclass
class Customer(DataClassJsonMixin):
name: str
email: str
active: bool = True
# Same methods available as with decorator approach
customer = Customer("John", "john@example.com")
json_str = customer.to_json()# Type variables used in method signatures
A = TypeVar('A', bound="DataClassJsonMixin")
T = TypeVar('T')
# JSON-compatible types
Json = Union[dict, list, str, int, float, bool, None]
JsonData = Union[str, bytes, bytearray] # Accepted input types for from_json
# Schema type for marshmallow integration
SchemaType = TypeVar('SchemaType', bound='marshmallow.Schema')# Instance to JSON
person = Person("Alice", 25)
json_string = person.to_json()
# '{"name": "Alice", "age": 25}'
# Instance to dict
data_dict = person.to_dict()
# {'name': 'Alice', 'age': 25}# JSON to instance
json_data = '{"name": "Bob", "age": 30}'
person = Person.from_json(json_data)
# Dict to instance
dict_data = {'name': 'Charlie', 'age': 35}
person = Person.from_dict(dict_data)# Generate schema
schema = Person.schema()
# Validate and deserialize
try:
person = schema.loads('{"name": "David", "age": "invalid"}')
except ValidationError as e:
print(f"Validation failed: {e}")from dataclasses import dataclass
from typing import List, Optional
from datetime import datetime
@dataclass_json
@dataclass
class Order:
id: str
items: List[str]
customer: Optional[str] = None
created_at: datetime = None
# Handles nested structures automatically
order = Order("12345", ["item1", "item2"], "Alice", datetime.now())
json_str = order.to_json()
restored_order = Order.from_json(json_str)Install with Tessl CLI
npx tessl i tessl/pypi-dataclasses-json