Write out enum values as strings
Is your feature request related to a problem? Please describe.
The protobuf specification says that JSON should serialize enum values to string and accept integer or string values, see below. It would be nice if we could enable this behaviour in protobuf_to_pydantic.
- https://protobuf.dev/programming-guides/proto3/#json
Describe the solution you'd like E.g., serialize
enum Foo {
FOO_UNSPECIFIED = 0;
FOO_BAR = 1;
}
values as, e.g.
"FOO_BAR"
rather than
1
Describe alternatives you've considered N/A
Additional context
- https://protobuf.dev/programming-guides/proto3/#json
In actual use, the best practice for enum is to use the int type. In the following example, although both ParseDict and MessageToDict support int and str enums, the int type is the best choice, otherwise there is no unification.
syntax = "proto3";
package demo;
enum SexType {
man = 0;
women = 1;
}
message UserMessage {
string uid=1;
int32 age=2;
float height=3;
SexType sex=4;
}
from demo_pb2 import import SexType, UserMessage
from google.protobuf.json_format import ParseDict, MessageToDict
# print attr value
print(UserMessage(sex=1))
# >>>>> sex: women
print(UserMessage(sex="women"))
# >>>>> sex: women
# print dict to msg attr value
print(ParseDict({"sex": 1}, UserMessage).sex)
# >>>>> 1
print(ParseDict({"sex": "women"}, UserMessage).sex)
# >>>>> 1
# print msg to dict value
print(MessageToDict(UserMessage(sex=1)))
# >>>>> {'sex': 'women'}
print(MessageToDict(UserMessage(sex="women")))
# >>>>> {'sex': 'women'}
That doesn't mean I don't want to get this done though, it's just that I can't think of a better solution at the moment, and if you can provide one then I'll be more than happy to move forward and resolve this.
In addition to this, proto ecology compatibility needs to be considered, for example, the validation rules in PGV are handled for int types https://github.com/bufbuild/protoc-gen-validate?tab=readme-ov-file#enums