or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

core-serialization.mddocs/

0

# Core Serialization

1

2

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.

3

4

## Capabilities

5

6

### Decorator Approach

7

8

The `@dataclass_json` decorator adds JSON methods directly to dataclass definitions, providing the most convenient integration with existing code.

9

10

```python { .api }

11

def dataclass_json(

12

_cls: Optional[Type[T]] = None,

13

*,

14

letter_case: Optional[LetterCase] = None,

15

undefined: Optional[Union[str, Undefined]] = None

16

) -> Union[Callable[[Type[T]], Type[T]], Type[T]]:

17

"""

18

Class decorator that adds JSON serialization methods to a dataclass.

19

20

Parameters:

21

- _cls: The dataclass to decorate (automatically provided)

22

- letter_case: Case conversion strategy for field names

23

- undefined: How to handle undefined parameters during deserialization

24

25

Returns:

26

The decorated class with added JSON methods

27

"""

28

```

29

30

Usage example:

31

32

```python

33

from dataclasses import dataclass

34

from dataclasses_json import dataclass_json, LetterCase, Undefined

35

36

@dataclass_json(letter_case=LetterCase.CAMEL, undefined=Undefined.EXCLUDE)

37

@dataclass

38

class Product:

39

product_name: str

40

unit_price: float

41

in_stock: bool

42

43

# This automatically adds: to_json, from_json, to_dict, from_dict, schema methods

44

```

45

46

### Mixin Class Approach

47

48

The `DataClassJsonMixin` provides the same functionality through inheritance, useful when you prefer composition over decoration.

49

50

```python { .api }

51

class DataClassJsonMixin:

52

"""

53

Abstract base class providing JSON serialization methods.

54

Dataclasses should inherit from this class to gain JSON capabilities.

55

"""

56

57

dataclass_json_config: Optional[dict]

58

59

def to_json(

60

self,

61

*,

62

skipkeys: bool = False,

63

ensure_ascii: bool = True,

64

check_circular: bool = True,

65

allow_nan: bool = True,

66

indent: Optional[Union[int, str]] = None,

67

separators: Optional[Tuple[str, str]] = None,

68

default: Optional[Callable] = None,

69

sort_keys: bool = False,

70

**kw

71

) -> str:

72

"""

73

Serialize the dataclass instance to a JSON string.

74

75

Parameters: Same as json.dumps() plus:

76

- All standard json.dumps() keyword arguments are supported

77

78

Returns:

79

JSON string representation of the dataclass

80

"""

81

82

def to_dict(self, encode_json: bool = False) -> Dict[str, Json]:

83

"""

84

Convert the dataclass instance to a dictionary.

85

86

Parameters:

87

- encode_json: If True, encode values for JSON compatibility

88

89

Returns:

90

Dictionary representation of the dataclass

91

"""

92

93

@classmethod

94

def from_json(

95

cls: Type[A],

96

s: JsonData,

97

*,

98

parse_float=None,

99

parse_int=None,

100

parse_constant=None,

101

infer_missing: bool = False,

102

**kw

103

) -> A:

104

"""

105

Create a dataclass instance from a JSON string.

106

107

Parameters:

108

- s: JSON string to deserialize

109

- parse_float, parse_int, parse_constant: JSON parsing options

110

- infer_missing: Infer missing fields from defaults

111

- **kw: Additional json.loads() arguments

112

113

Returns:

114

New instance of the dataclass

115

"""

116

117

@classmethod

118

def from_dict(

119

cls: Type[A],

120

kvs: Json,

121

*,

122

infer_missing: bool = False

123

) -> A:

124

"""

125

Create a dataclass instance from a dictionary.

126

127

Parameters:

128

- kvs: Dictionary with field values

129

- infer_missing: Infer missing fields from defaults

130

131

Returns:

132

New instance of the dataclass

133

"""

134

135

@classmethod

136

def schema(

137

cls: Type[A],

138

*,

139

infer_missing: bool = False,

140

only=None,

141

exclude=(),

142

many: bool = False,

143

context=None,

144

load_only=(),

145

dump_only=(),

146

partial: bool = False,

147

unknown=None

148

) -> "SchemaType[A]":

149

"""

150

Generate a marshmallow schema for the dataclass.

151

152

Parameters:

153

- infer_missing: Infer missing fields from defaults

154

- only: Fields to include (None means all)

155

- exclude: Fields to exclude

156

- many: Handle multiple instances

157

- context: Schema context

158

- load_only: Fields for deserialization only

159

- dump_only: Fields for serialization only

160

- partial: Allow partial data

161

- unknown: How to handle unknown fields

162

163

Returns:

164

marshmallow.Schema instance for validation

165

"""

166

```

167

168

Usage example:

169

170

```python

171

from dataclasses import dataclass

172

from dataclasses_json import DataClassJsonMixin

173

174

@dataclass

175

class Customer(DataClassJsonMixin):

176

name: str

177

email: str

178

active: bool = True

179

180

# Same methods available as with decorator approach

181

customer = Customer("John", "john@example.com")

182

json_str = customer.to_json()

183

```

184

185

## Type Definitions

186

187

```python { .api }

188

# Type variables used in method signatures

189

A = TypeVar('A', bound="DataClassJsonMixin")

190

T = TypeVar('T')

191

192

# JSON-compatible types

193

Json = Union[dict, list, str, int, float, bool, None]

194

JsonData = Union[str, bytes, bytearray] # Accepted input types for from_json

195

196

# Schema type for marshmallow integration

197

SchemaType = TypeVar('SchemaType', bound='marshmallow.Schema')

198

```

199

200

## Common Usage Patterns

201

202

### Basic Serialization

203

204

```python

205

# Instance to JSON

206

person = Person("Alice", 25)

207

json_string = person.to_json()

208

# '{"name": "Alice", "age": 25}'

209

210

# Instance to dict

211

data_dict = person.to_dict()

212

# {'name': 'Alice', 'age': 25}

213

```

214

215

### Basic Deserialization

216

217

```python

218

# JSON to instance

219

json_data = '{"name": "Bob", "age": 30}'

220

person = Person.from_json(json_data)

221

222

# Dict to instance

223

dict_data = {'name': 'Charlie', 'age': 35}

224

person = Person.from_dict(dict_data)

225

```

226

227

### Schema Validation

228

229

```python

230

# Generate schema

231

schema = Person.schema()

232

233

# Validate and deserialize

234

try:

235

person = schema.loads('{"name": "David", "age": "invalid"}')

236

except ValidationError as e:

237

print(f"Validation failed: {e}")

238

```

239

240

### Complex Types

241

242

```python

243

from dataclasses import dataclass

244

from typing import List, Optional

245

from datetime import datetime

246

247

@dataclass_json

248

@dataclass

249

class Order:

250

id: str

251

items: List[str]

252

customer: Optional[str] = None

253

created_at: datetime = None

254

255

# Handles nested structures automatically

256

order = Order("12345", ["item1", "item2"], "Alice", datetime.now())

257

json_str = order.to_json()

258

restored_order = Order.from_json(json_str)

259

```