FK82
FK82

Reputation: 5075

How do you create a Protobuf Struct from a Python Dict?

I get the following attribute error

AttributeError: 'Struct' object has no attribute 'fields'

if I want to use the update method of google.protobuf.internal.well_known_types.Struct

Protobuf version is 3.71.


MWE:

from google.protobuf.internal.well_known_types import Struct

s = Struct()
s.update({"key": "value"})

The bigger context of this question is that I want to create a message with a google.protobuf.Struct field in python for sending to pass to the generated RPC client.

Can anyone help?

Upvotes: 16

Views: 25314

Answers (2)

Aleh
Aleh

Reputation: 826

Should be as simple as

from google.protobuf.struct_pb2 import Struct
from google.protobuf import json_format

s = Struct()
s.update({"key": "value"})

json_format.MessageToDict(s)

Upvotes: 6

FK82
FK82

Reputation: 5075

Ok, I immediately found out how to do this after writing the question. Leaving the answer for anyone else who might end up having this problem.

We have to import Struct from google.protobuf.struct_pb2. Then update will work without a problem.

Hence,

from google.protobuf.struct_pb2 import Struct

s = Struct()
s.update({"key": "value"})

will return an object with representation

fields {
  key: "key"
  value {
    string_value: "value"
  }
}

Upvotes: 26

Related Questions