嘿,我知道 Java 中有一个解决方案,我很想知道是否有人知道用于将 JSON 对象或文件转换为 protobuf 格式的 Python 3 解决方案。我会接受 或 ,因为转换为对象是微不足道的。在 stackoverflow 网站上搜索时,我只找到了 protobuf->json 的示例,但没有找到相反的示例。有一个非常古老的存储库可以做到这一点,但它是在 Python 2 中,而我们的管道是 Python 3。我们一如既往地感谢任何帮助。
最佳答案
您正在寻找的库是 google.protobuf.json_format
。您可以按照 README
here 中的说明安装它。该库与 Python >= 2.7 兼容。
使用示例:
给定这样的 protobuf 消息:
message Thing {
string first = 1;
bool second = 2;
int32 third = 3;
}
您可以从 Python dict
或 JSON 字符串转到 protobuf,如下所示:
import json
from google.protobuf.json_format import Parse, ParseDict
d = {
"first": "a string",
"second": True,
"third": 123456789
}
message = ParseDict(d, Thing())
# or
message = Parse(json.dumps(d), Thing())
print(message.first) # "a string"
print(message.second) # True
print(message.third) # 123456789
或者从 protobuf 到 Python dict
或 JSON 字符串:
from google.protobuf.json_format import MessageToDict, MessageToJson
message_as_dict = MessageToDict(message)
message_as_dict['first'] # == 'a string'
message_as_dict['second'] # == True
message_as_dict['third'] # == 123456789
# or
message_as_json_str = MessageToJson(message)
关于python - Python 中的 JSON 到 Protobuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345426/