105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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 | 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).items()}
# filter out excluded attributes
if excluded_attributes:
excluded_att_keys = set()
for att in attributes.keys():
for excl_att in excluded_attributes:
if excl_att in att:
excluded_att_keys.add(att)
attributes = {att: val for att, val in attributes.items() if att not in excluded_att_keys}
for att, val in attributes.items():
if isinstance(val, dict):
att = f"collection:dict.{att}"
elif isinstance(val, (list, set, tuple, bytes, bytearray)):
att = f"collection:{derive_custom_object_key(val.__class__)}.{att}"
elif isinstance(val, Path):
att = f"path.{att}"
elif isinstance(val, Callable):
att = f"callable.{att}"
elif isinstance(val, datetime):
att = f"datetime.{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:{derive_custom_object_key(val.__class__)}"
else:
att = f"UNSERIALIZABLE.{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
|