0
# Core Serialization Functions
1
2
Essential functions for converting Python objects to/from JSON strings. These are the primary public APIs that most users will interact with for basic serialization needs.
3
4
## Capabilities
5
6
### Object Encoding
7
8
Converts Python objects to JSON strings with extensive configuration options for controlling serialization behavior.
9
10
```python { .api }
11
def encode(
12
value,
13
unpicklable=True,
14
make_refs=True,
15
keys=False,
16
max_depth=None,
17
reset=True,
18
backend=None,
19
warn=False,
20
context=None,
21
max_iter=None,
22
use_decimal=False,
23
numeric_keys=False,
24
use_base85=False,
25
fail_safe=None,
26
indent=None,
27
separators=None,
28
include_properties=False,
29
handle_readonly=False,
30
) -> str:
31
"""
32
Return a JSON formatted representation of value, a Python object.
33
34
Parameters:
35
- value: The Python object to encode
36
- unpicklable (bool): If False, creates simpler JSON without restoration metadata
37
- make_refs (bool): If False, disables referencing support for id()-identical objects
38
- keys (bool): If True, encodes non-string dictionary keys instead of coercing to strings
39
- max_depth (int): Maximum recursion depth before using repr()
40
- reset (bool): Whether to reset the pickler state (typically True)
41
- backend (JSONBackend): Custom JSON backend to use
42
- warn (bool): If True, warns when objects cannot be pickled
43
- context (Pickler): Pre-built Pickler object to use
44
- max_iter (int): Maximum items to consume from iterators
45
- use_decimal (bool): Allow Decimal instances to pass-through
46
- numeric_keys (bool): Leave numeric keys as-is (backend dependent)
47
- use_base85 (bool): Use base85 encoding for binary data
48
- fail_safe (callable): Function to call when encoding fails
49
- indent (int): JSON pretty-printing indentation
50
- separators (tuple): JSON separators for compact output
51
- include_properties (bool): Include property attributes in serialization
52
- handle_readonly (bool): Handle read-only attributes specially
53
54
Returns:
55
JSON string representation of the object
56
"""
57
```
58
59
**Usage Example:**
60
61
```python
62
import jsonpickle
63
64
class Person:
65
def __init__(self, name, age):
66
self.name = name
67
self.age = age
68
69
person = Person("Alice", 30)
70
71
# Basic encoding
72
json_str = jsonpickle.encode(person)
73
74
# Encoding without restoration metadata (simpler JSON)
75
simple_json = jsonpickle.encode(person, unpicklable=False)
76
77
# Pretty-printed JSON
78
formatted_json = jsonpickle.encode(person, indent=2)
79
80
# Encoding with custom depth limit
81
shallow_json = jsonpickle.encode(person, max_depth=1)
82
```
83
84
### Object Decoding
85
86
Converts JSON strings back to Python objects with safety and compatibility options.
87
88
```python { .api }
89
def decode(
90
string,
91
backend=None,
92
context=None,
93
keys=False,
94
reset=True,
95
safe=True,
96
classes=None,
97
v1_decode=False,
98
on_missing='ignore',
99
handle_readonly=False,
100
):
101
"""
102
Convert a JSON string into a Python object.
103
104
Parameters:
105
- string (str): JSON string to decode
106
- backend (JSONBackend): Custom JSON backend to use
107
- context (Unpickler): Pre-built Unpickler object to use
108
- keys (bool): If True, decodes non-string dictionary keys
109
- reset (bool): Whether to reset the unpickler state
110
- safe (bool): If False, enables eval() for backwards compatibility (insecure)
111
- classes (class/list/dict): Classes to make available during construction
112
- v1_decode (bool): Enable v1 format compatibility
113
- on_missing (str/callable): How to handle missing classes ('ignore', 'warn', 'error', or function)
114
- handle_readonly (bool): Handle read-only attributes properly
115
116
Returns:
117
Restored Python object
118
"""
119
```
120
121
**Usage Example:**
122
123
```python
124
import jsonpickle
125
126
# Basic decoding
127
json_str = '{"py/object": "person.Person", "name": "Alice", "age": 30}'
128
person = jsonpickle.decode(json_str)
129
130
# Safe decoding with local classes
131
local_classes = {'Person': Person}
132
person = jsonpickle.decode(json_str, classes=local_classes)
133
134
# Decoding with error handling for missing classes
135
person = jsonpickle.decode(json_str, on_missing='warn')
136
137
# Custom missing class handler
138
def handle_missing(class_name):
139
print(f"Class {class_name} not found")
140
return None
141
142
person = jsonpickle.decode(json_str, on_missing=handle_missing)
143
```
144
145
### JSON Compatibility Functions
146
147
Aliases providing compatibility with the standard json module's interface.
148
149
```python { .api }
150
dumps = encode
151
loads = decode
152
```
153
154
**Usage Example:**
155
156
```python
157
import jsonpickle
158
159
# Use like json.dumps/loads
160
obj = {'name': 'Alice', 'items': [1, 2, 3]}
161
json_str = jsonpickle.dumps(obj)
162
restored = jsonpickle.loads(json_str)
163
```
164
165
## Error Handling
166
167
The decode function may raise `ClassNotFoundError` when a class cannot be found during unpickling, depending on the `on_missing` parameter setting.
168
169
## Security Considerations
170
171
- Always use `safe=True` (default) when decoding untrusted data
172
- The `unpicklable=False` option creates simpler, safer JSON output
173
- Consider validating input data before decoding
174
- Never decode data from untrusted sources without proper validation