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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:27:55  来源:igfitidea点击:

Protobuf to json in python

pythonjsonprotocol-buffers

提问by exHash

I have an object that I de-serialize using protobufin Python. When I print the object it looks like a python object, however when I try to convert it to jsonI 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 jsonpicklewith 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库:

  1. It is accessible from pypi so you can simply pip install protobuf-to-dictor include it in a requirements.txt
  2. dictcan be converted to json and might be more useful than a json string
  1. 它可以从 pypi 访问,因此您可以简单地pip install protobuf-to-dict或将其包含在requirements.txt
  2. 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)