Reputation: 461
I'm trying to define a list of dictionaries in my .proto
All the examples I've found provide a dictionary with a single key, value pair:
message Pair {
string key = 1;
string value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
or something like:
message Dictionary {
message Pair {
map<string, string> values = 1;
}
repeated Pair pairs = 1;
}
but how would I handle a larger dictionary of mixed types?
{
'k1': 1,
'k2': 2,
'k3': 'three',
'k4': [1,2,3]
}
To further complicate things, once I've defined the dictionary of mixed values I need to create a message that is a list of these dictionaries. I assume that is as easy as creating a another repeated message with the dictionary nested:
message DictList {
repeated Dictionary dlist = 1;
}
Upvotes: 1
Views: 3903
Reputation: 874
Few ideas I came up with:
oneof
for value (https://developers.google.com/protocol-buffers/docs/proto3#oneof). That could solve the problem, e.g.message Value {
oneof oneof_values {
string svalue = 1;
int ivalue = 2;
...
}
}
message Pair {
string key = 1;
Value value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
You can't use map
or repeated
inside of oneof
though.
You could use optional fields and define them all as values in message definition. Then set only those, you actually use.
You could use wrappers, or known types, e.g. Value
: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value
for the Value
, it could be used like this:
map<string, google.protobuf.Value> dict = 1;
struct
(as suggested by for_stack), could be seen here: How do you create a Protobuf Struct from a Python Dict?Upvotes: 1