Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
FK82 Avatar asked May 25 '19 09:05

FK82


People also ask

What is a Protobuf struct?

Struct. `Struct` represents a structured data value, consisting of fields which map to dynamically typed values. In some languages, `Struct` might be supported by a native representation.

How do you use the DICT method?

Python dict() FunctionIf a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object. If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.


1 Answers

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"
  }
}
like image 92
FK82 Avatar answered Oct 02 '22 08:10

FK82