Protobuf to json in python

后端 未结 2 997
我在风中等你
我在风中等你 2020-12-13 23:57

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

相关标签:
2条回答
  • 2020-12-14 00:24

    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)
    
    0 讨论(0)
  • 2020-12-14 00:32

    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
    0 讨论(0)
提交回复
热议问题