[Python] How can a nested Protobuf Struct be parsed to a Python dict?

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

  1. Stack

    Stack Membro Participativo

    Single level Protobuf Struct fields can be parsed to Python dicts by passing the Struct to the Python dict. However, this does not work with nested dicts. Is there an officially supported method to convert nested Protobuf structs to dicts?

    from google.protobuf.struct_pb2 import Struct

    simple_struct = Struct()
    simple_struct.update({"hi": 1, "there": 2})
    print(dict(simple_struct))

    nested_struct = Struct()
    nested_struct.update({"hi": 1, "over": {"there": 23}})
    print(dict(nested_struct))


    # Output
    {'there': 2.0, 'hi': 1.0}
    {'hi': 1.0, 'over': fields {
    key: "there"
    value {
    number_value: 23.0
    }
    }
    }

    Continue reading...

Compartilhe esta Página