[Python] Python How to convert complex nested classes into dictionary

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a couple of classes instantiate basic types like str, int, float, list, dict's but also other classes that contains similar types. Essentially I have nested layers of objects. It is converted this way so data can be represented as objects and manipulated later. Once all the processing is done I want to export the data into a dictionary so it can be stored as a Json object on a database. Is this common? Are there libraries that help you do this.

    So far I was going to implement a function that converts the top level class and nested objects into dictionary nested output. I'm worried I will get stack overflow from the recursion I will be using to

    def getObjectAsDict(self):
    d = {}

    for name_of_attr in dir(some_class):
    if name_of_attr.startswith("_"):
    continue

    value_of_attr = getattr(some_class, name_of_attr)

    if isinstance(value_of_attr, str):
    pass
    elif isinstance(value_of_attr, int):
    pass
    elif isinstance(value_of_attr, float):
    pass
    elif isinstance(value_of_attr, bool):
    pass
    elif isinstance(value_of_attr, list):
    for idx, item in enumerate(value_of_attr):
    # some recursion logic here
    elif isinstance(value_of_attr, dict):
    for key, value in value_of_attr.items():
    # some recursion logic here
    elif isinstance(value_of_attr, ComplexObject):
    value_of_attr = value_of_attr.getObjectAsDict()
    # some recursion logic here
    else:
    continue
    d[name_of_attr] = value_of_attr

    Continue reading...

Compartilhe esta Página