タイトルが示すように、次のような別のメッセージを含む protobuf メッセージがあります。
syntax = "proto3";
message Message
{
message SubMessage {
int32 number = 1;
}
SubMessage subMessage = 1;
}
Myexample.json
は空です (これは、どこでもデフォルト値を意味します):
{
}
私のpythonスクリプトでは、このメッセージを次のように読みました:
example_json = open("example.json", "r").read()
example_message = example.Message()
google.protobuf.json_format.Parse(example_json, example_message)
そして、その値を確認すると、example_message.subMessage.number
どちら0
が正しいですか。
ここで、すべての値が存在する辞書に変換したいと思います。デフォルト値も含まれます。変換にはメソッドを使用しますgoogle.protobuf.json_format.MessageToDict()
。しかし、ご存知かもしれMessageToDict()
ませんが、私がそうするように指示することなくデフォルト値をシリアライズしません(この質問のように: Protobuf doesn't serialize default values )。そこで、次including_default_value_fields=True
の呼び出しに引数を追加しましたMessageToDict()
。
protobuf.MessageToDict(example_message, including_default_value_fields=True)
戻り値:
{}
私が期待したものの代わりに:
{'subMessage': {'number': 0}}
protobuf のコード内のコメント (ここにあります: https://github.com/protocolbuffers/protobuf/blob/master/python/google/protobuf/json_format.py ) は、この動作を確認します。
included_default_value_fields: True の場合、単一のプリミティブ フィールド、繰り返しフィールド、およびマップ フィールドは常にシリアル化されます。False の場合、空でないフィールドのみをシリアル化します。特異メッセージ フィールドと oneof フィールドは、このオプションの影響を受けません。
では、ネストされたメッセージ内のデフォルト値であっても、すべての値を含む dict を取得するにはどうすればよいでしょうか?
興味深いことに、私example.json
がこのように見えるとき:
{
"subMessage" : {
"number" : 0
}
}
期待される出力が得られます。しかし、example.json
すべての値が書き出されることを確認できないため、これはオプションではありません。