protobuf 到 python 中的 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19734617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Protobuf to json in python
提问by exHash
I have an object that I de-serialize using protobuf
in Python. When I print the object it looks like a python object, however when I try to convert it to json
I have all sorts of problems.
我有一个protobuf
在 Python 中使用反序列化的对象。当我打印对象时,它看起来像一个 python 对象,但是当我尝试将它转换为时,json
我遇到了各种各样的问题。
For example, if I use json.dumps()
I get that the object (the generated code from protoc) does not contain a _ dict_ error.
例如,如果我使用json.dumps()
我得到对象(从 protoc 生成的代码)不包含 _ dict_ 错误。
If I use jsonpickle I get UnicodeDecodeError: 'utf8' codec can't decode byte 0x9d in position 97: invalid start byte
.
如果我使用 jsonpickle 我得到UnicodeDecodeError: 'utf8' codec can't decode byte 0x9d in position 97: invalid start byte
.
Test code below is using jsonpickle
with the error shown above.
下面的测试代码正在使用jsonpickle
上面显示的错误。
if len(sys.argv) < 2:
print ("Error: missing ser file")
sys.exit()
else :
fileLocation = sys.argv[1]
org = BuildOrgObject(fileLocation)
org = org.Deserialize()
#print (org)
jsonObj = jsonpickle.encode(org)
print (jsonObj)
回答by Kevin Hill
If you need to go straight to json take a look at the protobuf-to-jsonlibrary, but you'll have to install that manually.
如果您需要直接使用 json,请查看protobuf-to-json库,但您必须手动安装它。
But I would recommend that you use the protobuf-to-dictlibrary instead for a few reasons:
但出于以下几个原因,我建议您改用protobuf-to-dict库:
- It is accessible from pypi so you can simply
pip install protobuf-to-dict
or include it in arequirements.txt
dict
can be converted to json and might be more useful than a json string
- 它可以从 pypi 访问,因此您可以简单地
pip install protobuf-to-dict
或将其包含在requirements.txt
dict
可以转换为 json 并且可能比 json 字符串更有用
回答by denis-sumin
I'd recommend using protobuf?json converters from google's protobuflibrary:
我建议使用谷歌protobuf库中的protobuf?json 转换器:
from google.protobuf.json_format import MessageToJson
jsonObj = MessageToJson(org)
Refer to protobuf package API: https://developers.google.com/protocol-buffers/docs/reference/python/(see module google.protobuf.json_format).
参考 protobuf 包 API:https: //developers.google.com/protocol-buffers/docs/reference/python/(参见模块 google.protobuf.json_format)。
Note you can also serialise the protobuf to a Dict
请注意,您还可以将 protobuf 序列化为 Dict
from google.protobuf.json_format import MessageToDict
dict_obj = MessageToDict(org)