JsonPreSerializer
Utility for converting arbitrary Python objects into JSON-safe, serialization-friendly structures. Handles cycles, dataclasses, Pydantic models, enums, slots, sensitive fields, and datetime values.
Methods
create_stack_elements(node_collection) staticmethod
Convert a normalized container (dict/list/tuple/set) into BFS queue elements (child, id(child)) for traversal.
Parameters
node_collection (
object) A normalized container (dict, list, tuple, set, or primitive) whose children should be added to the BFS traversal queue.
Returns
list[tuple[object, int]] - A list of
(child_object, id(child_object))tuples.
get_iterable(variable) staticmethod
Parameters
variable (
object) A callable, dict, or iterable used to supply key–value pairs during normalization.
Returns
object - Either:
the result of calling the variable (if callable)
dict.items()for a dictthe variable itself (if already iterable)
prepare_for_serialization(context_var) staticmethod
Fully normalize an object graph into a JSON-serializable structure. Performs a two-pass BFS to:
shallow-normalize each node
rebuild references to avoid cycles
remove private fields
convert models/enums/datetimes into JSON-safe values
Parameters
context_var (
object) Root object whose full object graph will be normalized for JSON serialization.
Returns
object - A fully JSON-safe structure composed only of dictionaries, lists, primitive types, and ISO-8601 datetimes.
Raises
RuntimeError - If an unexpected object graph structure prevents traversal or normalization.
shallow_normalize(node) staticmethod
Convert a single object into a JSON-safe representation. Handles:
Sensitive fields -
<redacted>Enum - enum.value
dict/list/tuple/set - shallow copies
Pydantic/dataclass (dict, slots) - dict form
datetime - ISO-8601 string
Parameters
node (
object) A single Python object to convert into a shallow JSON-friendly form.
Returns
object - A shallow-normalized version of the object. This may be:
a dict
a list
a primitive value
an enum value
an ISO-8601 string (for datetime)
<redacted>for sensitive fields