python - Python 中的 JSON 到 Protobuf

标签 python json protocol-buffers

嘿,我知道 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)

The documentation for the json_format module is here

关于python - Python 中的 JSON 到 Protobuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345426/

相关文章:

wcf - 使用 jQuery 访问 JSON WCF 服务时未找到 404

python - 如何在 Tensorflow 中显示隐藏层输出

c++ - 如何使用 Gmock 模拟不带运算符 == 的函数参数

戈朗。替换不是真正的 go 包的模块路径

python - 虹膜上随机均匀分布

python - conda 错误 : Cannot link a source that does not exist

python - 在保持时间戳的同时将 XLSX 转换为 CSV

json - Windows 终端选项卡快捷方式不起作用、类型不正确、预期对象

Python try/except ... 函数总是返回 false

Python 创建 Google 存储桶