0
# Advanced Pickler and Unpickler Classes
1
2
Low-level serialization classes providing fine-grained control over the encoding/decoding process, including state management and reusability for advanced use cases.
3
4
## Capabilities
5
6
### Pickler Class
7
8
Advanced serialization class for converting Python objects to JSON-serializable dictionaries with extensive configuration options.
9
10
```python { .api }
11
class Pickler:
12
def __init__(
13
self,
14
unpicklable=True,
15
make_refs=True,
16
max_depth=None,
17
backend=None,
18
keys=False,
19
warn=False,
20
max_iter=None,
21
numeric_keys=False,
22
use_decimal=False,
23
use_base85=False,
24
fail_safe=None,
25
include_properties=False,
26
handle_readonly=False,
27
):
28
"""
29
Initialize a Pickler with configuration options.
30
31
Parameters: Same as encode() function
32
"""
33
34
def reset(self):
35
"""
36
Reset the pickler's internal state for reuse.
37
Call this between pickling sessions to clear object references.
38
"""
39
40
def flatten(self, obj):
41
"""
42
Convert a Python object to a JSON-serializable dictionary.
43
44
Parameters:
45
- obj: Python object to flatten
46
47
Returns:
48
JSON-serializable dictionary representation
49
"""
50
```
51
52
**Usage Example:**
53
54
```python
55
import jsonpickle
56
57
# Create a reusable pickler
58
pickler = jsonpickle.Pickler(unpicklable=False, make_refs=False)
59
60
# Flatten multiple objects
61
obj1 = {'name': 'Alice', 'age': 30}
62
obj2 = {'name': 'Bob', 'age': 25}
63
64
flattened1 = pickler.flatten(obj1)
65
flattened2 = pickler.flatten(obj2)
66
67
# Reset between sessions if needed
68
pickler.reset()
69
70
# Configure pickler for different needs
71
secure_pickler = jsonpickle.Pickler(
72
unpicklable=False,
73
max_depth=3,
74
warn=True
75
)
76
```
77
78
### Unpickler Class
79
80
Advanced deserialization class for converting JSON data back to Python objects with safety controls and state management.
81
82
```python { .api }
83
class Unpickler:
84
def __init__(
85
self,
86
backend=None,
87
keys=False,
88
safe=True,
89
v1_decode=False,
90
on_missing='ignore',
91
handle_readonly=False,
92
):
93
"""
94
Initialize an Unpickler with configuration options.
95
96
Parameters: Same as decode() function
97
"""
98
99
def reset(self):
100
"""
101
Reset the unpickler's internal state for reuse.
102
Call this between unpickling sessions to clear object references.
103
"""
104
105
def restore(self, obj):
106
"""
107
Convert a JSON-serializable dictionary back to a Python object.
108
109
Parameters:
110
- obj: JSON-serializable dictionary to restore
111
112
Returns:
113
Restored Python object
114
"""
115
116
def register_classes(self, classes):
117
"""
118
Register classes for object construction during unpickling.
119
120
Parameters:
121
- classes: Single class, sequence of classes, or dict mapping names to classes
122
"""
123
```
124
125
**Usage Example:**
126
127
```python
128
import jsonpickle
129
130
# Create a reusable unpickler
131
unpickler = jsonpickle.Unpickler(safe=True, on_missing='warn')
132
133
# Register local classes
134
class LocalClass:
135
def __init__(self, value):
136
self.value = value
137
138
unpickler.register_classes([LocalClass])
139
140
# Restore multiple objects
141
json_data1 = {'py/object': '__main__.LocalClass', 'value': 42}
142
json_data2 = {'py/object': '__main__.LocalClass', 'value': 24}
143
144
obj1 = unpickler.restore(json_data1)
145
obj2 = unpickler.restore(json_data2)
146
147
# Reset between sessions if needed
148
unpickler.reset()
149
150
# Configure for different security levels
151
secure_unpickler = jsonpickle.Unpickler(
152
safe=True,
153
on_missing='error',
154
classes={'SafeClass': LocalClass}
155
)
156
```
157
158
### Context Usage
159
160
Both Pickler and Unpickler can be used as context objects in the main encode/decode functions for performance optimization.
161
162
```python
163
import jsonpickle
164
165
# Reuse pickler context for multiple operations
166
pickler = jsonpickle.Pickler(unpicklable=False)
167
unpickler = jsonpickle.Unpickler(safe=True)
168
169
# Use contexts in encode/decode
170
obj1 = {'data': [1, 2, 3]}
171
obj2 = {'data': [4, 5, 6]}
172
173
json1 = jsonpickle.encode(obj1, context=pickler, reset=False)
174
json2 = jsonpickle.encode(obj2, context=pickler, reset=False)
175
176
restored1 = jsonpickle.decode(json1, context=unpickler, reset=False)
177
restored2 = jsonpickle.decode(json2, context=unpickler, reset=False)
178
179
# Reset when done
180
pickler.reset()
181
unpickler.reset()
182
```
183
184
## State Management
185
186
Both classes maintain internal state for object references and type handling:
187
188
- **Object References**: Track id()-identical objects to preserve identity
189
- **Type Registry**: Cache class lookups for performance
190
- **Backend State**: Maintain JSON encoder/decoder configuration
191
192
Use `reset()` to clear this state between independent serialization sessions.
193
194
## Performance Considerations
195
196
- Reusing Pickler/Unpickler instances avoids repeated initialization overhead
197
- The `reset=False` parameter preserves object references across multiple calls
198
- Context objects are particularly useful for batch processing operations