pythonprotocol-buffers

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


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
  }
}
}

Solution

  • There is now a built-in method method to recursively convert a Struct to native python objects: google.protobuf.json_format.MessageToDict()

    Here's the documentation for this method: https://googleapis.dev/python/protobuf/latest/google/protobuf/json_format.html

    from google.protobuf.json_format import MessageToDict
    from google.protobuf.struct_pb2 import Struct
    
    struct = Struct()
    struct.update({"hi": 1, "over": [23, 45, None, 6.7, "there", [8.9, "10"], {"key": None}]})
    out = MessageToDict(struct)
    print(out)
    

    Output:

    {'hi': 1.0, 'over': [23.0, 45.0, None, 6.7, 'there', [8.9, '10'], {'key': None}]}