是否可以从 protobuf pb2 文件生成 JSON/Dict Python 对象?

Is it possible to generate JSON/Dict Python object from a protobuf pb2 file?

我正在尝试确定是否可以将 protobuf 描述符或对象从 prototool 生成的 pb2 文件转换为 JSON/Dict Python 对象。这是我到目前为止所做的:

  1. 我用 TopConfig 写了一个 config.proto 文件。
  2. 我运行prototool generate config.proto生成config_pb2.py.
  3. 现在我想在 Python 中生成一个 JSON/Dict 对象,默认值为 TopConfig
from google.protobuf.json_format import MessageToDict, MessageToJson
import config_pb2.py

j = MessageToJson(config_pb2.py.TopConfig())
d = MessageToDict(config_pb2.py.TopConfig())

这两种情况下的 {} 字典都是空的。我错过了什么?

好的,所以我自己想出来了。

我的错误是我的 TopConfig 只有其他 messages 嵌套在其中但没有其他数据字段。 MessageToDict 仅适用于未嵌套的 messages,并且不会显示 enumoneof 数据。

MessageToDict(config_pb2.py.TopConfig())  # Will produce {}
MessageToDict(config_pb2.py.LowestConfig())  # Will produce {'k1': v1, 'k2': v2}

请注意,它不会显示 nested messagesenumoneof,您可以轻松地通过逻辑来检查这些内容。

config_pb2.py.TopConfig().DESCRIPTOR.oneofs  # True if it has oneofs type
config_pb2.py.TopConfig().DESCRIPTOR.enum_types  # True if it has enum type

希望这 post 对以后的人有所帮助。

json_format 将省略“未设置”字段。在您的示例中,TopConfig() 创建一个空的 TopConfig 实例,即未设置任何字段。因此,{} 是该对象的正确 JSON 表示。

然而,including_default_value_fieldsMessageToDict 几乎就是您想要的:

including_default_value_fields: If True, singular primitive fields,
  repeated fields, and map fields will always be serialized.  If
  False, only serialize non-empty fields.  Singular message fields
  and oneof fields are not affected by this option.

我说“几乎”是因为仍然不会出现空的子消息字段。