Reputation: 8195
Protocol Buffers have a method that can turn a single pb instance into a JSON object.
https://googleapis.dev/python/protobuf/latest/google/protobuf/json_format.html
But is there an inverse of this method? I want a way of initializing a new Protocol Buffer instance from a generic data-structure, or a JSON document?
Background: I receive a feed of data a message bus. The messages on this feed are provided in XML. The vendor provides XML schemas. I've already converted those XSDs to equivalent .protos - now I want to convert every message sent on this feed into an equivalent Protobuf message.
The benefit of doing this will be smaller messages which cost less for us to store on our side. I'm looking for way to initialize a new Protobuf object from the content of the XML, preferably in a single operation.
Edit: A follow on question related to the suggestion below.
Upvotes: 0
Views: 3403
Reputation: 4391
You can use parse to do that
Copy paste:
google.protobuf.json_format.Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None)¶ Parses a JSON representation of a protocol message into a message. Parameters
text – Message JSON representation.
message – A protocol buffer message to merge into.
ignore_unknown_fields – If True, do not raise errors for unknown fields.
descriptor_pool – A Descriptor Pool for resolving types. If None use the default.
Returns The same message passed as argument. Raises:: ParseError: On JSON parsing problems.
Upvotes: 1