Package google :: Package protobuf :: Module json_format
[hide private]
[frames] | no frames]

Module json_format

source code

Contains routines for printing protocol messages in JSON format.

Simple usage example:

  # Create a proto object and serialize it to a json format string.
  message = my_proto_pb2.MyMessage(foo='bar')
  json_string = json_format.MessageToJson(message)

  # Parse a json format string to proto object.
  message = json_format.Parse(json_string, my_proto_pb2.MyMessage())


Author: jieluo@google.com (Jie Luo)

Classes [hide private]
  Error
Top-level module error for json_format.
  SerializeToJsonError
Thrown if serialization to JSON fails.
  ParseError
Thrown in case of parsing error.
  _Printer
JSON format printer for protocol message.
  _Parser
JSON format parser for protocol message.
Functions [hide private]
 
MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False, indent=2, sort_keys=False, use_integers_for_enums=False, descriptor_pool=None)
Converts protobuf message to JSON format.
source code
 
MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None)
Converts protobuf message to a dictionary.
source code
 
_IsMapEntry(field) source code
 
_IsWrapperMessage(message_descriptor) source code
 
_DuplicateChecker(js) source code
 
_CreateMessageFromTypeUrl(type_url, descriptor_pool)
Creates a message from a type URL.
source code
 
Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None)
Parses a JSON representation of a protocol message into a message.
source code
 
ParseDict(js_dict, message, ignore_unknown_fields=False, descriptor_pool=None)
Parses a JSON dictionary representation into a message.
source code
 
_ConvertScalarFieldValue(value, field, require_str=False)
Convert a single scalar field value.
source code
 
_ConvertInteger(value)
Convert an integer.
source code
 
_ConvertFloat(value)
Convert an floating point number.
source code
 
_ConvertBool(value, require_str)
Convert a boolean value.
source code
Variables [hide private]
  _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
  _INT_TYPES = frozenset([1, 2, 3, 4])
  _INT64_TYPES = frozenset([2, 4])
  _FLOAT_TYPES = frozenset([5, 6])
  _INFINITY = 'Infinity'
  _NEG_INFINITY = '-Infinity'
  _NAN = 'NaN'
  _UNPAIRED_SURROGATE_PATTERN = re.compile(r'[\ud800-\udbff](?![...
  _VALID_EXTENSION_NAME = re.compile(r'\[[a-zA-Z0-9\._]*\]$')
  _INT_OR_FLOAT = (<type 'int'>, <type 'long'>, <type 'float'>)
  _WKTJSONMETHODS = {'google.protobuf.Any': ['_AnyMessageToJsonO...
  __package__ = 'google.protobuf'
Function Details [hide private]

MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False, indent=2, sort_keys=False, use_integers_for_enums=False, descriptor_pool=None)

source code 
Converts protobuf message to JSON format.

Args:
  message: The protocol buffers message instance to serialize.
  including_default_value_fields: If True, singular primitive fields,
      repeated fields, and map fields will always be serialized.  If
      False, only serialize non-empty fields.  Singular message fields
      and oneof fields are not affected by this option.
  preserving_proto_field_name: If True, use the original proto field
      names as defined in the .proto file. If False, convert the field
      names to lowerCamelCase.
  indent: The JSON object will be pretty-printed with this indent level.
      An indent level of 0 or negative will only insert newlines.
  sort_keys: If True, then the output will be sorted by field names.
  use_integers_for_enums: If true, print integers instead of enum names.
  descriptor_pool: A Descriptor Pool for resolving types. If None use the
      default.

Returns:
  A string containing the JSON formatted protocol buffer message.

MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None)

source code 
Converts protobuf message to a dictionary.

When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.

Args:
  message: The protocol buffers message instance to serialize.
  including_default_value_fields: If True, singular primitive fields,
      repeated fields, and map fields will always be serialized.  If
      False, only serialize non-empty fields.  Singular message fields
      and oneof fields are not affected by this option.
  preserving_proto_field_name: If True, use the original proto field
      names as defined in the .proto file. If False, convert the field
      names to lowerCamelCase.
  use_integers_for_enums: If true, print integers instead of enum names.
  descriptor_pool: A Descriptor Pool for resolving types. If None use the
      default.

Returns:
  A dict representation of the protocol buffer message.

Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None)

source code 
Parses a JSON representation of a protocol message into a message.

Args:
  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.

ParseDict(js_dict, message, ignore_unknown_fields=False, descriptor_pool=None)

source code 
Parses a JSON dictionary representation into a message.

Args:
  js_dict: Dict representation of a JSON message.
  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.

_ConvertScalarFieldValue(value, field, require_str=False)

source code 
Convert a single scalar field value.

Args:
  value: A scalar value to convert the scalar field value.
  field: The descriptor of the field to convert.
  require_str: If True, the field value must be a str.

Returns:
  The converted scalar field value

Raises:
  ParseError: In case of convert problems.

_ConvertInteger(value)

source code 
Convert an integer.

Args:
  value: A scalar value to convert.

Returns:
  The integer value.

Raises:
  ParseError: If an integer couldn't be consumed.

_ConvertBool(value, require_str)

source code 
Convert a boolean value.

Args:
  value: A scalar value to convert.
  require_str: If True, value must be a str.

Returns:
  The bool parsed.

Raises:
  ParseError: If a boolean value couldn't be consumed.


Variables Details [hide private]

_UNPAIRED_SURROGATE_PATTERN

Value:
re.compile(r'[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\\
udc00-\udfff]')

_WKTJSONMETHODS

Value:
{'google.protobuf.Any': ['_AnyMessageToJsonObject',
                         '_ConvertAnyMessage'],
 'google.protobuf.Duration': ['_GenericMessageToJsonObject',
                              '_ConvertGenericMessage'],
 'google.protobuf.FieldMask': ['_GenericMessageToJsonObject',
                               '_ConvertGenericMessage'],
 'google.protobuf.ListValue': ['_ListValueMessageToJsonObject',
                               '_ConvertListValueMessage'],
...