JSON 到 Python 中的 Protobuf
JSON to Protobuf in Python
嘿,我知道 Java 中有一个解决方案,我很想知道是否有人知道 Python 3 转换 JSON 对象或文件的解决方案转换为 protobuf 格式。我会接受或者因为转换为对象是微不足道的。搜索 Whosebug 站点,我只找到了 protobuf->json 的示例,但没有找到相反的示例。有一个非常古老的回购协议可能会执行此操作,但它在 Python 2 中,我们的管道是 Python 3。任何帮助一如既往,不胜感激。
您要找的图书馆是google.protobuf.json_format
. You can install it with the directions in the 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)
嘿,我知道 Java 中有一个解决方案,我很想知道是否有人知道 Python 3 转换 JSON 对象或文件的解决方案转换为 protobuf 格式。我会接受或者因为转换为对象是微不足道的。搜索 Whosebug 站点,我只找到了 protobuf->json 的示例,但没有找到相反的示例。有一个非常古老的回购协议可能会执行此操作,但它在 Python 2 中,我们的管道是 Python 3。任何帮助一如既往,不胜感激。
您要找的图书馆是google.protobuf.json_format
. You can install it with the directions in the 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)