Posted on November 22, 2023 | #python

thumbnail

Convert python objects into dictionaries

Turning dictionaries into python classes with the **kwargs syntax is pretty common. This is how to go the other way around:

def convert_to_serializable(obj: Any) -> Any:
    if hasattr(obj, "__dict__"):
        return dict([(k, convert_to_serializable(v)) for k, v in vars(obj).items()])
    if isinstance(obj, list):
        return [convert_to_serializable(el) for el in obj]
    return obj  # Default for primitive types

This snippet will turn objects into dictionaries with their respective members. Beware - it doesn’t discriminate. Private members prefixed with _ will be included too! Arrays are traversed and converted. Primitives are left alone.

Warning: If you have a loop somewhere in the data, this will absolutely cause a recursion error!!!

This may be an alternative to a custom JSONEncoder. Anyways - you are ready to write the output into a file with json.dump(file) no problemo!