JSON to Protobuf in Python

Viewed 19664

Hey I know there is a solution for this in Java, I'm curious to know if anyone knows of a Python 3 solution for converting a JSON object or file into protobuf format. I would accept either or as converting to an object is trivial. Searching the stackoverflow site, I only found examples of protobuf->json, but not the other way around. There is one extremely old repo that may do this but it is in Python 2 and our pipeline is Python 3. Any help is as always, appreciated.

1 Answers

The library you're looking for is google.protobuf.json_format. You can install it with the directions in the README here. The library is compatible with Python >= 2.7.

Example usage:

Given a protobuf message like this:

message Thing {
    string first = 1;
    bool second = 2;
    int32 third = 3;
}

You can go from Python dict or JSON string to protobuf like:

import json

from google.protobuf.json_format import Parse, ParseDict

d = {
    "first": "a string",
    "second": True,
    "third": 123456789
}

message = ParseDict(d, Thing())
# or
message = Parse(json.dumps(d), Thing())    

print(message.first)  # "a string"
print(message.second) # True
print(message.third)  # 123456789

or from protobuf to Python dict or JSON string:

from google.protobuf.json_format import MessageToDict, MessageToJson

message_as_dict = MessageToDict(message)
message_as_dict['first']  # == 'a string'
message_as_dict['second'] # == True
message_as_dict['third']  # == 123456789
# or
message_as_json_str = MessageToJson(message)

The documentation for the json_format module is here.

Related