Protobuf to json in python

Protobuf to json in python

Id recommend using protobuf↔json converters from googles protobuf library:

from google.protobuf.json_format import MessageToJson

json_obj = MessageToJson(org)

You can also serialise the protobuf to a dictionary:

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

Refer to the protobuf package API documentation: (see module google.protobuf.json_format).

If you need to go straight to json take a look at the protobuf-to-json library, but youll 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

Protobuf to json in python

You can also user SerializeToString.


Leave a Reply

Your email address will not be published. Required fields are marked *