Given, a serialized protobuf (protocol buffer) output in the string format. I want to convert it to a python dictionary.
Suppose, this is the serialized protobuf, given as a python string:
person {
info {
name: John
age: 20
website: "https://mywebsite.com"
eligible: True
}
}
I want to convert the above python string to a python dictionary data
, given as:
data = {
"person": {
"info": {
"name": "John",
"age": 20,
"website": "https://mywebsite.com",
"eligible": True,
}
}
}
I can write a python script to do the conversion, as follows:
- Append commas on every line not ending with curly brackets.
- Add an extra colon before the opening curly bracket.
- Surround every individual key and value pair with quotes.
- Finally, use the
json.loads()
method to convert it to a Python dictionary.
I wonder whether this conversion can be achieved using a simpler or a standard method, already available in protocol buffers. So, apart from the manual scripting using the steps I mentioned above, is there a better or a standard method available to convert the serialized protobuf output to a python dictionary?
MessageToDict
: googleapis.dev/python/protobuf/latest/google/protobuf/… – JeremyjerezMessageToJson(message, ...)
, themessage
parameter isThe protocol buffer message instance to serialize.
, so it's an instance of the protocol buffer. I need conversion from a plain string to JSON, not from a protocol buffer object. – MoorParseFromString
either. You have a binary string not a purely human-readable string and so you should take care converting it differently to JSON. See: developers.google.com/protocol-buffers/docs/encoding – Jeremyjerez