1

I am reading the documentation and cannot seem to find anything explicit.

Let's say that I have a protobuf definition MyObject.pb. I create an object of type MyObject and set each of its fields to some meaningful value. And assume all the values are proto primitives (int, floats, strings...).

Say that I store these values as a representing string that follows the same syntax as the definition.

e.g if MyObject.pb looks like:

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;
}

And the associated saved file looks like:

message Person {
  required string name = aStringName;
  required int32 id = 100;
  optional string email = ex@mple.com;
}

Is there a way to automatically initialize the protobuffer by giving the constructor the path to the representing string as an argument? or do you have to do the parsing manually?

Makogan
  • 8,208
  • 7
  • 44
  • 112

1 Answers1

3

Although it doesn't use exactly the same syntax as the definition, you can use the google.protobuf.text_format module to parse a more human-readable representation of a message. Specifically, the Merge method parses such a string into a protocol buffer, and the MessageToString method turns a protocol buffer into a string.

For your example message, the text representation would look like this:

name: "aStringName"
id: 100
email "ex@mple.com"

It can also handle nested messages. (See this other answer for more detail.)

Harry Cutts
  • 1,352
  • 11
  • 25