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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281 | def serialize(
obj: Any,
pyobjson_base_custom_subclasses: List[Type],
excluded_attributes: List[str],
class_keys_for_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 regex pattern
matching exclusions.
class_keys_for_excluded_attributes (Optional[list[str]], optional): List of Python class keys for which to
exclude attributes provided in excluded_attributes during serialization. If no class keys are provided,
all attributes provided in excluded_attributes will be excluded from all classes during serialization.
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, class_keys_for_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):
if isfunction(val):
callable_type = f"function{DLIM}"
elif ismethod(val):
callable_type = f"method{DLIM}"
else:
callable_type = None
att = f"callable{DLIM}{callable_type if callable_type else ''}{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, class_keys_for_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, class_keys_for_excluded_attributes)
for k, v in obj.items()
}
elif isinstance(obj, (list, set, tuple)):
return [
serialize(v, pyobjson_base_custom_subclasses, excluded_attributes, class_keys_for_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
|