Created
April 23, 2020 15:32
-
-
Save martyphee/0dc842b68314d575ee5189d39bfc4a1d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
syntax = "proto3"; | |
package tutorial; | |
message BillingAddress { | |
string address1 = 1; | |
string address2 = 2; | |
} | |
message Person { | |
string name = 1; | |
int32 id = 2; | |
string email = 3; | |
enum PhoneType { | |
MOBILE = 0; | |
HOME = 1; | |
WORK = 2; | |
} | |
message PhoneNumber { | |
string number = 1; | |
PhoneType type = 2; | |
} | |
repeated PhoneNumber phones = 4; | |
BillingAddress billing_address = 5; | |
} | |
message AddressBook { | |
repeated Person people = 1; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from proto.address_book_pb2 import Person | |
from google.protobuf.json_format import MessageToJson, Parse, MessageToDict | |
def main(): | |
person = Person() | |
person.id = 1234 | |
person.name = "John Doe" | |
person.email = "[email protected]" | |
phone = person.phones.add() | |
phone.number = "555-4321" | |
phone.type = Person.HOME | |
billingAddress = person.billing_address | |
billingAddress.address1 = "89 Mexfield Rd" | |
billingAddress.address2 = "London" | |
print(person) | |
# print(MessageToJson(person)) | |
# person2 = Person() | |
json = MessageToJson(person, preserving_proto_field_name=True) | |
person2 = Parse(json, Person()) | |
print(person2) | |
print("Dictionary") | |
print(MessageToDict(person, preserving_proto_field_name=True)) | |
if __name__ == "__main__": | |
# execute only if run as a script | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "John Doe", | |
"id": 1234, | |
"email": "[email protected]", | |
"phones": [ | |
{ | |
"number": "555-4321", | |
"type": "HOME" | |
} | |
], | |
"billing_address": { | |
"address1": "89 Westminster Rd", | |
"address2": "London" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment