在Python中将Protobuf转换为JSON [英] Protobuf to json in python
问题描述
我有一个对象,该对象在Python中使用protobuf
反序列化.当我打印对象时,它看起来像一个python对象,但是当我尝试将其转换为json
时,我遇到了各种各样的问题.
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.
例如,如果我使用json.dumps()
,我会得到该对象(从protoc生成的代码)不包含_ dict _错误.
For example, if I use json.dumps()
I get that the object (the generated code from protoc) does not contain a _ dict _ error.
如果我使用jsonpickle,则会得到UnicodeDecodeError: 'utf8' codec can't decode byte 0x9d in position 97: invalid start byte
.
If I use jsonpickle I get UnicodeDecodeError: 'utf8' codec can't decode byte 0x9d in position 97: invalid start byte
.
下面的测试代码正在使用jsonpickle
并显示上面的错误.
Test code below is using jsonpickle
with the error shown above.
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)
推荐答案
我建议使用Google的 protobuf 库:
I'd recommend using protobuf↔json converters from google's protobuf library:
from google.protobuf.json_format import MessageToJson
jsonObj = MessageToJson(org)
请参阅protobuf程序包API: https://developers.google.com /protocol-buffers/docs/reference/python/(请参阅模块google.protobuf.json_format).
Refer to protobuf package API: https://developers.google.com/protocol-buffers/docs/reference/python/ (see module google.protobuf.json_format).
请注意,您也可以将protobuf序列化为Dict
Note you can also serialise the protobuf to a Dict
from google.protobuf.json_format import MessageToDict
dict_obj = MessageToDict(org)
这篇关于在Python中将Protobuf转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!