protobuf MessageToJson删除值为0的字段

2024-05-13 17:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本来接收protobuf,将它们转换为json对象,并将它们推送到另一个服务。我使用json.loads(MessageToJson(protobuf))将protobuf转换为python字典对象。稍后我用json.dumps(dictionary)将其转换回json。在

我有一个带有可选枚举字段的proto,例如:

enum C_TYPE
{
    AB = 0;
    BC = 1;
    CD = 2;
}

当我收到一个名为BC的proto时,一切都如我所料。当我收到一个名为AB的proto时,该字段将被忽略——它不会出现在python字典或后续的json转储中。我找到的一个解决方法是使用json.loads(MessageToJson(protobuf, including_default_value_fields=True)),但这将为所有丢失的字段创建默认值,而不仅仅是具有0枚举的字段。这意味着带有枚举0的字段丢失了-但事实并非如此!在

当枚举字段设置为0时,检索该字段值的正确方法是什么?在


Tags: 对象方法脚本jsondictionary字典abtype
1条回答
网友
1楼 · 发布于 2024-05-13 17:34:10

没有正确的方法,我没有正确的定义我的原型。对于枚举字段,第一个值是默认值。这意味着,如果一个protobuf没有设置值,它将被设置为默认值,并且在转换为json时被忽略(除非您希望保留所有默认值)

因此,建议对默认值使用丢弃的名称,以便能够正确地区分设置它的时间。i、 e.我应该把我的计划定义为:

enum C_TYPE
{
    NONE = 0;
    AB = 1;
    BC = 2;
    CD = 3;
}

来自Protobuf Documentation on Optional Fields And Default Values

For enums, the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

另外,来自issue on golang/protobuf

This is working as intended. proto3 zero-values are omitted in the JSON format too. The zero-value should be a "throwaway" value: it's also what you will see if the sender of a serialized message sets the field to an invalid or unrecognized value.

相关问题 更多 >