0
# Core Serialization
1
2
Primary functions for converting Python objects to JSON-compatible formats and vice versa. These functions handle automatic type detection, nested objects, and provide extensive customization options.
3
4
## Capabilities
5
6
### Object to JSON Serialization
7
8
```python { .api }
9
def dump(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
10
"""
11
Serialize the given Python object to a JSON equivalent type (dict, list, int, str, etc.).
12
13
Parameters:
14
- obj: Any Python instance to be serialized
15
- cls: Optional type to serialize obj as (must have __slots__ defined)
16
- strict: Bool to determine if serializer should be strict (only dump known attributes)
17
- fork_inst: Optional fork instance for separate serializer configuration
18
- **kwargs: Additional keyword arguments passed to serializer functions
19
20
Returns:
21
JSON-compatible Python object (dict, list, str, int, float, bool, None)
22
"""
23
24
def dumps(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
25
"""
26
Serialize the given Python object to a JSON string.
27
28
Parameters:
29
- obj: Any Python instance to be serialized
30
- cls: Optional type to serialize obj as
31
- strict: Bool for strict serialization mode
32
- fork_inst: Optional fork instance
33
- **kwargs: Additional arguments including JSON formatting options
34
35
Returns:
36
str: JSON string representation of the object
37
"""
38
39
def dumpb(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
40
"""
41
Serialize the given Python object to JSON bytes.
42
43
Parameters:
44
- obj: Any Python instance to be serialized
45
- cls: Optional type to serialize obj as
46
- strict: Bool for strict serialization mode
47
- fork_inst: Optional fork instance
48
- **kwargs: Additional arguments including encoding options
49
50
Returns:
51
bytes: JSON bytes representation of the object
52
"""
53
```
54
55
### JSON to Object Deserialization
56
57
```python { .api }
58
def load(json_obj, cls=None, *, strict=False, fork_inst=None, attr_getters=None, **kwargs):
59
"""
60
Deserialize the given JSON object to a Python object of the specified type.
61
62
Parameters:
63
- json_obj: JSON-compatible object (dict, list, str, int, float, bool, None)
64
- cls: Target Python type to deserialize into
65
- strict: Bool for strict deserialization mode
66
- fork_inst: Optional fork instance
67
- attr_getters: Dict mapping attribute names to getter functions
68
- **kwargs: Additional arguments passed to deserializer functions
69
70
Returns:
71
Instance of cls type reconstructed from json_obj
72
73
Raises:
74
- DeserializationError: If json_obj cannot be deserialized to cls
75
- ValidationError: If validation fails on the deserialized object
76
"""
77
78
def loads(s, cls=None, *, strict=False, fork_inst=None, **kwargs):
79
"""
80
Deserialize a JSON string to a Python object of the specified type.
81
82
Parameters:
83
- s: JSON string to deserialize
84
- cls: Target Python type to deserialize into
85
- strict: Bool for strict deserialization mode
86
- fork_inst: Optional fork instance
87
- **kwargs: Additional arguments including JSON parsing options
88
89
Returns:
90
Instance of cls type reconstructed from JSON string
91
92
Raises:
93
- DecodeError: If JSON string is malformed
94
- DeserializationError: If deserialization fails
95
"""
96
97
def loadb(b, cls=None, *, strict=False, fork_inst=None, **kwargs):
98
"""
99
Deserialize JSON bytes to a Python object of the specified type.
100
101
Parameters:
102
- b: JSON bytes to deserialize
103
- cls: Target Python type to deserialize into
104
- strict: Bool for strict deserialization mode
105
- fork_inst: Optional fork instance
106
- **kwargs: Additional arguments including encoding options
107
108
Returns:
109
Instance of cls type reconstructed from JSON bytes
110
111
Raises:
112
- DecodeError: If JSON bytes are malformed
113
- DeserializationError: If deserialization fails
114
"""
115
```
116
117
## Usage Examples
118
119
### Basic Object Serialization
120
121
```python
122
import jsons
123
from dataclasses import dataclass
124
from typing import List
125
from datetime import datetime
126
127
@dataclass
128
class Task:
129
title: str
130
completed: bool
131
due_date: datetime
132
133
@dataclass
134
class Project:
135
name: str
136
tasks: List[Task]
137
138
# Create complex nested objects
139
project = Project(
140
name="Website Redesign",
141
tasks=[
142
Task("Design mockups", False, datetime(2023, 12, 15)),
143
Task("Implement frontend", False, datetime(2023, 12, 30))
144
]
145
)
146
147
# Serialize to JSON-compatible dict
148
project_dict = jsons.dump(project)
149
print(project_dict)
150
# {
151
# 'name': 'Website Redesign',
152
# 'tasks': [
153
# {'title': 'Design mockups', 'completed': False, 'due_date': '2023-12-15T00:00:00'},
154
# {'title': 'Implement frontend', 'completed': False, 'due_date': '2023-12-30T00:00:00'}
155
# ]
156
# }
157
158
# Serialize to JSON string
159
project_json = jsons.dumps(project, indent=2)
160
print(project_json) # Pretty-printed JSON string
161
162
# Serialize to JSON bytes
163
project_bytes = jsons.dumpb(project)
164
print(type(project_bytes)) # <class 'bytes'>
165
```
166
167
### Object Deserialization
168
169
```python
170
import jsons
171
from dataclasses import dataclass
172
from typing import List
173
174
@dataclass
175
class User:
176
name: str
177
age: int
178
emails: List[str]
179
180
# Deserialize from dict
181
user_data = {
182
'name': 'John Doe',
183
'age': 30,
184
'emails': ['john@example.com', 'john.doe@work.com']
185
}
186
187
user = jsons.load(user_data, User)
188
print(user.name) # "John Doe"
189
print(user.emails[0]) # "john@example.com"
190
191
# Deserialize from JSON string
192
user_json = '{"name": "Jane Smith", "age": 25, "emails": ["jane@example.com"]}'
193
user = jsons.loads(user_json, User)
194
print(user.name) # "Jane Smith"
195
196
# Deserialize from JSON bytes
197
user_bytes = b'{"name": "Bob Wilson", "age": 35, "emails": []}'
198
user = jsons.loadb(user_bytes, User)
199
print(user.age) # 35
200
```
201
202
### Strict Mode
203
204
```python
205
import jsons
206
from dataclasses import dataclass
207
208
@dataclass
209
class Person:
210
name: str
211
age: int
212
213
# Extra fields are normally ignored
214
person_data = {'name': 'Alice', 'age': 30, 'extra_field': 'ignored'}
215
person = jsons.load(person_data, Person) # Works fine
216
217
# Strict mode raises an error for extra fields
218
try:
219
person = jsons.load(person_data, Person, strict=True)
220
except jsons.DeserializationError as e:
221
print(f"Strict mode error: {e}")
222
```
223
224
### Custom Type Handling
225
226
```python
227
import jsons
228
from decimal import Decimal
229
from datetime import datetime
230
from uuid import UUID
231
232
# jsons handles many built-in types automatically
233
data = {
234
'price': Decimal('19.99'),
235
'created_at': datetime.now(),
236
'id': UUID('12345678-1234-5678-1234-567812345678')
237
}
238
239
# Serialize complex types
240
serialized = jsons.dump(data)
241
print(serialized)
242
# {
243
# 'price': '19.99',
244
# 'created_at': '2023-12-01T10:30:00.123456',
245
# 'id': '12345678-1234-5678-1234-567812345678'
246
# }
247
248
# Deserialize back with proper types
249
original_data = jsons.load(serialized, dict)
250
print(type(original_data['price'])) # <class 'str'> (needs type hint for proper restoration)
251
```