Protobuf to json in python

夙愿已清 提交于 2019-11-30 03:11:06
denis-sumin

I'd recommend using protobuf↔json converters from google's protobuf library:

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).

Note you can also serialise the protobuf to a Dict

from google.protobuf.json_format import MessageToDict
dict_obj = MessageToDict(org)
Kevin Hill

If you need to go straight to json take a look at the protobuf-to-json library, but you'll have to install that manually.

But I would recommend that you use the protobuf-to-dict library instead for a few reasons:

  1. It is accessible from pypi so you can simply pip install protobuf-to-dict or include it in a requirements.txt
  2. dict can be converted to json and might be more useful than a json string
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!