139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219 | def serialize(obj: Any, pyobjson_base_custom_subclasses: List[Type], excluded_attributes: List[str]) -> Any:
"""Recursive function to serialize custom Python objects into nested dictionaries for conversion to JSON.
Args:
obj (Any): Python object to serialize.
pyobjson_base_custom_subclasses (list[Type]): List of custom Python class subclasses.
excluded_attributes (list[str]): List of attributes to exclude from serialization. Supports substring matching
exclusions.
Returns:
dict[str, Any]: Serializable dictionary.
"""
if type(obj) in pyobjson_base_custom_subclasses:
serializable_obj = {}
attributes = {
k: v for k, v in unpack_custom_class_vars(obj, pyobjson_base_custom_subclasses, excluded_attributes).items()
}
for att, val in attributes.items():
if isinstance(val, dict):
# noinspection PyUnboundLocalVariable
if (
len(val) == 1
and (single_key := next(iter(val.keys())))
and single_key
in [derive_custom_object_key(subclass) for subclass in pyobjson_base_custom_subclasses]
):
# do nothing because attribute key for custom Python object is already formatted correctly by
# unpack custom_class_vars()
pass
else:
att = f"collection{DLIM}dict{DLIM}{att}"
elif isinstance(val, (list, set, tuple, bytes, bytearray)):
att = f"collection{DLIM}{derive_custom_object_key(val.__class__)}{DLIM}{att}"
elif isinstance(val, Path):
att = f"path{DLIM}{att}"
elif isinstance(val, Callable):
att = f"callable{DLIM}{att}"
elif isinstance(val, datetime):
att = f"datetime{DLIM}{att}"
else:
try:
json.dumps(val)
except TypeError as e:
if str(e) == f"Object of type {type(val).__name__} is not JSON serializable":
att = f"repr{DLIM}{derive_custom_object_key(val.__class__)}"
else:
att = f"{UNSERIALIZABLE}{DLIM}{derive_custom_object_key(val.__class__)}"
serializable_obj[att] = serialize(val, pyobjson_base_custom_subclasses, excluded_attributes)
return {derive_custom_object_key(obj.__class__): serializable_obj}
elif isinstance(obj, dict):
return {k: serialize(v, pyobjson_base_custom_subclasses, excluded_attributes) for k, v in obj.items()}
elif isinstance(obj, (list, set, tuple)):
return [serialize(v, pyobjson_base_custom_subclasses, excluded_attributes) for v in obj]
elif isinstance(obj, (bytes, bytearray)):
return b64encode(obj).decode("utf-8")
elif isinstance(obj, Path):
return str(obj)
elif isinstance(obj, Callable):
return derive_custom_callable_value(obj)
elif isinstance(obj, datetime):
return obj.isoformat()
else:
try:
json.dumps(obj)
except TypeError as e:
if str(e) == f"Object of type {type(obj).__name__} is not JSON serializable.":
return repr(obj)
else:
return UNSERIALIZABLE
return obj
|