blob: 4342755ad620b2b9c9396f3b7762e01f0559a126 [file] [log] [blame]
Jisi Liu46e8ff62015-10-05 11:59:43 -07001# Protocol Buffers - Google's data interchange format
2# Copyright 2008 Google Inc. All rights reserved.
3# https://developers.google.com/protocol-buffers/
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
Feng Xiaoe841bac2015-12-11 17:09:20 -080031"""Contains routines for printing protocol messages in JSON format.
32
33Simple usage example:
34
35 # Create a proto object and serialize it to a json format string.
36 message = my_proto_pb2.MyMessage(foo='bar')
37 json_string = json_format.MessageToJson(message)
38
39 # Parse a json format string to proto object.
40 message = json_format.Parse(json_string, my_proto_pb2.MyMessage())
41"""
Jisi Liu46e8ff62015-10-05 11:59:43 -070042
43__author__ = 'jieluo@google.com (Jie Luo)'
44
45import base64
Jisi Liu46e8ff62015-10-05 11:59:43 -070046import json
47import math
CH Albach5477f8c2016-01-29 18:10:50 -080048import six
Jie Luo2850a982015-10-09 17:07:03 -070049import sys
Jisi Liu46e8ff62015-10-05 11:59:43 -070050
51from google.protobuf import descriptor
CH Albach5477f8c2016-01-29 18:10:50 -080052from google.protobuf import symbol_database
Jisi Liu46e8ff62015-10-05 11:59:43 -070053
54_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
Jisi Liu46e8ff62015-10-05 11:59:43 -070055_INT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT32,
56 descriptor.FieldDescriptor.CPPTYPE_UINT32,
57 descriptor.FieldDescriptor.CPPTYPE_INT64,
58 descriptor.FieldDescriptor.CPPTYPE_UINT64])
59_INT64_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT64,
60 descriptor.FieldDescriptor.CPPTYPE_UINT64])
61_FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
62 descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
Feng Xiaoe841bac2015-12-11 17:09:20 -080063_INFINITY = 'Infinity'
64_NEG_INFINITY = '-Infinity'
65_NAN = 'NaN'
Jisi Liu46e8ff62015-10-05 11:59:43 -070066
67
Feng Xiaoe841bac2015-12-11 17:09:20 -080068class Error(Exception):
69 """Top-level module error for json_format."""
70
71
72class SerializeToJsonError(Error):
Jisi Liu46e8ff62015-10-05 11:59:43 -070073 """Thrown if serialization to JSON fails."""
74
75
Feng Xiaoe841bac2015-12-11 17:09:20 -080076class ParseError(Error):
Jisi Liu46e8ff62015-10-05 11:59:43 -070077 """Thrown in case of parsing error."""
78
79
80def MessageToJson(message, including_default_value_fields=False):
81 """Converts protobuf message to JSON format.
82
83 Args:
84 message: The protocol buffers message instance to serialize.
85 including_default_value_fields: If True, singular primitive fields,
86 repeated fields, and map fields will always be serialized. If
87 False, only serialize non-empty fields. Singular message fields
88 and oneof fields are not affected by this option.
89
90 Returns:
91 A string containing the JSON formatted protocol buffer message.
92 """
93 js = _MessageToJsonObject(message, including_default_value_fields)
94 return json.dumps(js, indent=2)
95
96
97def _MessageToJsonObject(message, including_default_value_fields):
98 """Converts message to an object according to Proto3 JSON Specification."""
99 message_descriptor = message.DESCRIPTOR
CH Albach5477f8c2016-01-29 18:10:50 -0800100 full_name = message_descriptor.full_name
Jisi Liu46e8ff62015-10-05 11:59:43 -0700101 if _IsWrapperMessage(message_descriptor):
102 return _WrapperMessageToJsonObject(message)
CH Albach5477f8c2016-01-29 18:10:50 -0800103 if full_name in _WKTJSONMETHODS:
104 return _WKTJSONMETHODS[full_name][0](
105 message, including_default_value_fields)
106 js = {}
107 return _RegularMessageToJsonObject(
108 message, js, including_default_value_fields)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700109
110
111def _IsMapEntry(field):
112 return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
113 field.message_type.has_options and
114 field.message_type.GetOptions().map_entry)
115
116
CH Albach5477f8c2016-01-29 18:10:50 -0800117def _RegularMessageToJsonObject(message, js, including_default_value_fields):
Jisi Liu46e8ff62015-10-05 11:59:43 -0700118 """Converts normal message according to Proto3 JSON Specification."""
Jisi Liu46e8ff62015-10-05 11:59:43 -0700119 fields = message.ListFields()
Feng Xiaoe841bac2015-12-11 17:09:20 -0800120 include_default = including_default_value_fields
Jisi Liu46e8ff62015-10-05 11:59:43 -0700121
122 try:
123 for field, value in fields:
124 name = field.camelcase_name
125 if _IsMapEntry(field):
126 # Convert a map field.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800127 v_field = field.message_type.fields_by_name['value']
Jisi Liu46e8ff62015-10-05 11:59:43 -0700128 js_map = {}
129 for key in value:
Jie Luo2850a982015-10-09 17:07:03 -0700130 if isinstance(key, bool):
131 if key:
132 recorded_key = 'true'
133 else:
134 recorded_key = 'false'
135 else:
136 recorded_key = key
Feng Xiaoe841bac2015-12-11 17:09:20 -0800137 js_map[recorded_key] = _FieldToJsonObject(
138 v_field, value[key], including_default_value_fields)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700139 js[name] = js_map
140 elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
141 # Convert a repeated field.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800142 js[name] = [_FieldToJsonObject(field, k, include_default)
143 for k in value]
Jisi Liu46e8ff62015-10-05 11:59:43 -0700144 else:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800145 js[name] = _FieldToJsonObject(field, value, include_default)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700146
147 # Serialize default value if including_default_value_fields is True.
148 if including_default_value_fields:
149 message_descriptor = message.DESCRIPTOR
150 for field in message_descriptor.fields:
151 # Singular message fields and oneof fields will not be affected.
152 if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and
153 field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or
154 field.containing_oneof):
155 continue
156 name = field.camelcase_name
157 if name in js:
158 # Skip the field which has been serailized already.
159 continue
160 if _IsMapEntry(field):
161 js[name] = {}
162 elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
163 js[name] = []
164 else:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800165 js[name] = _FieldToJsonObject(field, field.default_value)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700166
167 except ValueError as e:
168 raise SerializeToJsonError(
Feng Xiaoe841bac2015-12-11 17:09:20 -0800169 'Failed to serialize {0} field: {1}.'.format(field.name, e))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700170
171 return js
172
173
Feng Xiaoe841bac2015-12-11 17:09:20 -0800174def _FieldToJsonObject(
Jisi Liu46e8ff62015-10-05 11:59:43 -0700175 field, value, including_default_value_fields=False):
176 """Converts field value according to Proto3 JSON Specification."""
177 if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
178 return _MessageToJsonObject(value, including_default_value_fields)
179 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
180 enum_value = field.enum_type.values_by_number.get(value, None)
181 if enum_value is not None:
182 return enum_value.name
183 else:
184 raise SerializeToJsonError('Enum field contains an integer value '
185 'which can not mapped to an enum value.')
186 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
187 if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
188 # Use base64 Data encoding for bytes
189 return base64.b64encode(value).decode('utf-8')
190 else:
191 return value
192 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800193 return bool(value)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700194 elif field.cpp_type in _INT64_TYPES:
195 return str(value)
196 elif field.cpp_type in _FLOAT_TYPES:
197 if math.isinf(value):
198 if value < 0.0:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800199 return _NEG_INFINITY
Jisi Liu46e8ff62015-10-05 11:59:43 -0700200 else:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800201 return _INFINITY
Jisi Liu46e8ff62015-10-05 11:59:43 -0700202 if math.isnan(value):
Feng Xiaoe841bac2015-12-11 17:09:20 -0800203 return _NAN
Jisi Liu46e8ff62015-10-05 11:59:43 -0700204 return value
205
206
CH Albach5477f8c2016-01-29 18:10:50 -0800207def _AnyMessageToJsonObject(message, including_default):
208 """Converts Any message according to Proto3 JSON Specification."""
209 if not message.ListFields():
210 return {}
211 js = {}
212 type_url = message.type_url
213 js['@type'] = type_url
214 sub_message = _CreateMessageFromTypeUrl(type_url)
215 sub_message.ParseFromString(message.value)
216 message_descriptor = sub_message.DESCRIPTOR
217 full_name = message_descriptor.full_name
218 if _IsWrapperMessage(message_descriptor):
219 js['value'] = _WrapperMessageToJsonObject(sub_message)
220 return js
221 if full_name in _WKTJSONMETHODS:
222 js['value'] = _WKTJSONMETHODS[full_name][0](sub_message, including_default)
223 return js
224 return _RegularMessageToJsonObject(sub_message, js, including_default)
225
226
227def _CreateMessageFromTypeUrl(type_url):
228 # TODO(jieluo): Should add a way that users can register the type resolver
229 # instead of the default one.
230 db = symbol_database.Default()
231 type_name = type_url.split('/')[-1]
232 try:
233 message_descriptor = db.pool.FindMessageTypeByName(type_name)
234 except KeyError:
235 raise TypeError(
236 'Can not find message descriptor by type_url: {0}.'.format(type_url))
237 message_class = db.GetPrototype(message_descriptor)
238 return message_class()
239
240
241def _GenericMessageToJsonObject(message, unused_including_default):
242 """Converts message by ToJsonString according to Proto3 JSON Specification."""
243 # Duration, Timestamp and FieldMask have ToJsonString method to do the
244 # convert. Users can also call the method directly.
245 return message.ToJsonString()
246
247
248def _ValueMessageToJsonObject(message, unused_including_default=False):
249 """Converts Value message according to Proto3 JSON Specification."""
250 which = message.WhichOneof('kind')
251 # If the Value message is not set treat as null_value when serialize
252 # to JSON. The parse back result will be different from original message.
253 if which is None or which == 'null_value':
254 return None
255 if which == 'list_value':
256 return _ListValueMessageToJsonObject(message.list_value)
257 if which == 'struct_value':
258 value = message.struct_value
259 else:
260 value = getattr(message, which)
261 oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
262 return _FieldToJsonObject(oneof_descriptor, value)
263
264
265def _ListValueMessageToJsonObject(message, unused_including_default=False):
266 """Converts ListValue message according to Proto3 JSON Specification."""
267 return [_ValueMessageToJsonObject(value)
268 for value in message.values]
269
270
271def _StructMessageToJsonObject(message, unused_including_default=False):
272 """Converts Struct message according to Proto3 JSON Specification."""
273 fields = message.fields
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700274 return {key: _ValueMessageToJsonObject(fields[key])
275 for key in fields}
CH Albach5477f8c2016-01-29 18:10:50 -0800276
277
Jisi Liu46e8ff62015-10-05 11:59:43 -0700278def _IsWrapperMessage(message_descriptor):
279 return message_descriptor.file.name == 'google/protobuf/wrappers.proto'
280
281
282def _WrapperMessageToJsonObject(message):
Feng Xiaoe841bac2015-12-11 17:09:20 -0800283 return _FieldToJsonObject(
Jisi Liu46e8ff62015-10-05 11:59:43 -0700284 message.DESCRIPTOR.fields_by_name['value'], message.value)
285
286
287def _DuplicateChecker(js):
288 result = {}
289 for name, value in js:
290 if name in result:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800291 raise ParseError('Failed to load JSON: duplicate key {0}.'.format(name))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700292 result[name] = value
293 return result
294
295
296def Parse(text, message):
297 """Parses a JSON representation of a protocol message into a message.
298
299 Args:
300 text: Message JSON representation.
301 message: A protocol beffer message to merge into.
302
303 Returns:
304 The same message passed as argument.
305
306 Raises::
307 ParseError: On JSON parsing problems.
308 """
CH Albach5477f8c2016-01-29 18:10:50 -0800309 if not isinstance(text, six.text_type): text = text.decode('utf-8')
Jisi Liu46e8ff62015-10-05 11:59:43 -0700310 try:
Jie Luo2850a982015-10-09 17:07:03 -0700311 if sys.version_info < (2, 7):
312 # object_pair_hook is not supported before python2.7
313 js = json.loads(text)
314 else:
315 js = json.loads(text, object_pairs_hook=_DuplicateChecker)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700316 except ValueError as e:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800317 raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
CH Albach5477f8c2016-01-29 18:10:50 -0800318 _ConvertMessage(js, message)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700319 return message
320
321
322def _ConvertFieldValuePair(js, message):
323 """Convert field value pairs into regular message.
324
325 Args:
326 js: A JSON object to convert the field value pairs.
327 message: A regular protocol message to record the data.
328
329 Raises:
330 ParseError: In case of problems converting.
331 """
332 names = []
333 message_descriptor = message.DESCRIPTOR
334 for name in js:
335 try:
336 field = message_descriptor.fields_by_camelcase_name.get(name, None)
337 if not field:
338 raise ParseError(
339 'Message type "{0}" has no field named "{1}".'.format(
340 message_descriptor.full_name, name))
341 if name in names:
342 raise ParseError(
343 'Message type "{0}" should not have multiple "{1}" fields.'.format(
344 message.DESCRIPTOR.full_name, name))
345 names.append(name)
346 # Check no other oneof field is parsed.
347 if field.containing_oneof is not None:
348 oneof_name = field.containing_oneof.name
349 if oneof_name in names:
350 raise ParseError('Message type "{0}" should not have multiple "{1}" '
351 'oneof fields.'.format(
352 message.DESCRIPTOR.full_name, oneof_name))
353 names.append(oneof_name)
354
355 value = js[name]
356 if value is None:
357 message.ClearField(field.name)
358 continue
359
360 # Parse field value.
361 if _IsMapEntry(field):
362 message.ClearField(field.name)
363 _ConvertMapFieldValue(value, message, field)
364 elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
365 message.ClearField(field.name)
366 if not isinstance(value, list):
367 raise ParseError('repeated field {0} must be in [] which is '
Feng Xiaoe841bac2015-12-11 17:09:20 -0800368 '{1}.'.format(name, value))
CH Albach5477f8c2016-01-29 18:10:50 -0800369 if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
370 # Repeated message field.
371 for item in value:
Jisi Liu46e8ff62015-10-05 11:59:43 -0700372 sub_message = getattr(message, field.name).add()
CH Albach5477f8c2016-01-29 18:10:50 -0800373 # None is a null_value in Value.
374 if (item is None and
375 sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):
376 raise ParseError('null is not allowed to be used as an element'
377 ' in a repeated field.')
Jisi Liu46e8ff62015-10-05 11:59:43 -0700378 _ConvertMessage(item, sub_message)
CH Albach5477f8c2016-01-29 18:10:50 -0800379 else:
380 # Repeated scalar field.
381 for item in value:
382 if item is None:
383 raise ParseError('null is not allowed to be used as an element'
384 ' in a repeated field.')
Jisi Liu46e8ff62015-10-05 11:59:43 -0700385 getattr(message, field.name).append(
386 _ConvertScalarFieldValue(item, field))
387 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
388 sub_message = getattr(message, field.name)
389 _ConvertMessage(value, sub_message)
390 else:
391 setattr(message, field.name, _ConvertScalarFieldValue(value, field))
392 except ParseError as e:
393 if field and field.containing_oneof is None:
394 raise ParseError('Failed to parse {0} field: {1}'.format(name, e))
395 else:
396 raise ParseError(str(e))
397 except ValueError as e:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800398 raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700399 except TypeError as e:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800400 raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700401
402
403def _ConvertMessage(value, message):
404 """Convert a JSON object into a message.
405
406 Args:
407 value: A JSON object.
408 message: A WKT or regular protocol message to record the data.
409
410 Raises:
411 ParseError: In case of convert problems.
412 """
413 message_descriptor = message.DESCRIPTOR
CH Albach5477f8c2016-01-29 18:10:50 -0800414 full_name = message_descriptor.full_name
415 if _IsWrapperMessage(message_descriptor):
Jisi Liu46e8ff62015-10-05 11:59:43 -0700416 _ConvertWrapperMessage(value, message)
CH Albach5477f8c2016-01-29 18:10:50 -0800417 elif full_name in _WKTJSONMETHODS:
418 _WKTJSONMETHODS[full_name][1](value, message)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700419 else:
420 _ConvertFieldValuePair(value, message)
421
CH Albach5477f8c2016-01-29 18:10:50 -0800422
423def _ConvertAnyMessage(value, message):
424 """Convert a JSON representation into Any message."""
425 if isinstance(value, dict) and not value:
426 return
427 try:
428 type_url = value['@type']
429 except KeyError:
430 raise ParseError('@type is missing when parsing any message.')
431
432 sub_message = _CreateMessageFromTypeUrl(type_url)
433 message_descriptor = sub_message.DESCRIPTOR
434 full_name = message_descriptor.full_name
435 if _IsWrapperMessage(message_descriptor):
436 _ConvertWrapperMessage(value['value'], sub_message)
437 elif full_name in _WKTJSONMETHODS:
438 _WKTJSONMETHODS[full_name][1](value['value'], sub_message)
439 else:
440 del value['@type']
441 _ConvertFieldValuePair(value, sub_message)
442 # Sets Any message
443 message.value = sub_message.SerializeToString()
444 message.type_url = type_url
445
446
447def _ConvertGenericMessage(value, message):
448 """Convert a JSON representation into message with FromJsonString."""
449 # Durantion, Timestamp, FieldMask have FromJsonString method to do the
450 # convert. Users can also call the method directly.
451 message.FromJsonString(value)
452
453
454_INT_OR_FLOAT = six.integer_types + (float,)
455
456
457def _ConvertValueMessage(value, message):
458 """Convert a JSON representation into Value message."""
459 if isinstance(value, dict):
460 _ConvertStructMessage(value, message.struct_value)
461 elif isinstance(value, list):
462 _ConvertListValueMessage(value, message.list_value)
463 elif value is None:
464 message.null_value = 0
465 elif isinstance(value, bool):
466 message.bool_value = value
467 elif isinstance(value, six.string_types):
468 message.string_value = value
469 elif isinstance(value, _INT_OR_FLOAT):
470 message.number_value = value
471 else:
472 raise ParseError('Unexpected type for Value message.')
473
474
475def _ConvertListValueMessage(value, message):
476 """Convert a JSON representation into ListValue message."""
477 if not isinstance(value, list):
478 raise ParseError(
479 'ListValue must be in [] which is {0}.'.format(value))
480 message.ClearField('values')
481 for item in value:
482 _ConvertValueMessage(item, message.values.add())
483
484
485def _ConvertStructMessage(value, message):
486 """Convert a JSON representation into Struct message."""
487 if not isinstance(value, dict):
488 raise ParseError(
489 'Struct must be in a dict which is {0}.'.format(value))
490 for key in value:
491 _ConvertValueMessage(value[key], message.fields[key])
492 return
493
494
Jisi Liu46e8ff62015-10-05 11:59:43 -0700495def _ConvertWrapperMessage(value, message):
496 """Convert a JSON representation into Wrapper message."""
497 field = message.DESCRIPTOR.fields_by_name['value']
498 setattr(message, 'value', _ConvertScalarFieldValue(value, field))
499
500
501def _ConvertMapFieldValue(value, message, field):
502 """Convert map field value for a message map field.
503
504 Args:
505 value: A JSON object to convert the map field value.
506 message: A protocol message to record the converted data.
507 field: The descriptor of the map field to be converted.
508
509 Raises:
510 ParseError: In case of convert problems.
511 """
512 if not isinstance(value, dict):
513 raise ParseError(
CH Albach5477f8c2016-01-29 18:10:50 -0800514 'Map field {0} must be in a dict which is {1}.'.format(
515 field.name, value))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700516 key_field = field.message_type.fields_by_name['key']
517 value_field = field.message_type.fields_by_name['value']
518 for key in value:
519 key_value = _ConvertScalarFieldValue(key, key_field, True)
520 if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
521 _ConvertMessage(value[key], getattr(message, field.name)[key_value])
522 else:
523 getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(
524 value[key], value_field)
525
526
Feng Xiaoe841bac2015-12-11 17:09:20 -0800527def _ConvertScalarFieldValue(value, field, require_str=False):
Jisi Liu46e8ff62015-10-05 11:59:43 -0700528 """Convert a single scalar field value.
529
530 Args:
531 value: A scalar value to convert the scalar field value.
532 field: The descriptor of the field to convert.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800533 require_str: If True, the field value must be a str.
Jisi Liu46e8ff62015-10-05 11:59:43 -0700534
535 Returns:
536 The converted scalar field value
537
538 Raises:
539 ParseError: In case of convert problems.
540 """
541 if field.cpp_type in _INT_TYPES:
542 return _ConvertInteger(value)
543 elif field.cpp_type in _FLOAT_TYPES:
544 return _ConvertFloat(value)
545 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800546 return _ConvertBool(value, require_str)
Jisi Liu46e8ff62015-10-05 11:59:43 -0700547 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
548 if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
549 return base64.b64decode(value)
550 else:
551 return value
552 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
553 # Convert an enum value.
554 enum_value = field.enum_type.values_by_name.get(value, None)
555 if enum_value is None:
556 raise ParseError(
557 'Enum value must be a string literal with double quotes. '
558 'Type "{0}" has no value named {1}.'.format(
559 field.enum_type.full_name, value))
560 return enum_value.number
561
562
563def _ConvertInteger(value):
564 """Convert an integer.
565
566 Args:
567 value: A scalar value to convert.
568
569 Returns:
570 The integer value.
571
572 Raises:
573 ParseError: If an integer couldn't be consumed.
574 """
575 if isinstance(value, float):
Feng Xiaoe841bac2015-12-11 17:09:20 -0800576 raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700577
CH Albach5477f8c2016-01-29 18:10:50 -0800578 if isinstance(value, six.text_type) and value.find(' ') != -1:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800579 raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700580
581 return int(value)
582
583
584def _ConvertFloat(value):
585 """Convert an floating point number."""
586 if value == 'nan':
Feng Xiaoe841bac2015-12-11 17:09:20 -0800587 raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
Jisi Liu46e8ff62015-10-05 11:59:43 -0700588 try:
589 # Assume Python compatible syntax.
590 return float(value)
591 except ValueError:
592 # Check alternative spellings.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800593 if value == _NEG_INFINITY:
Jisi Liu46e8ff62015-10-05 11:59:43 -0700594 return float('-inf')
Feng Xiaoe841bac2015-12-11 17:09:20 -0800595 elif value == _INFINITY:
Jisi Liu46e8ff62015-10-05 11:59:43 -0700596 return float('inf')
Feng Xiaoe841bac2015-12-11 17:09:20 -0800597 elif value == _NAN:
Jisi Liu46e8ff62015-10-05 11:59:43 -0700598 return float('nan')
599 else:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800600 raise ParseError('Couldn\'t parse float: {0}.'.format(value))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700601
602
Feng Xiaoe841bac2015-12-11 17:09:20 -0800603def _ConvertBool(value, require_str):
Jisi Liu46e8ff62015-10-05 11:59:43 -0700604 """Convert a boolean value.
605
606 Args:
607 value: A scalar value to convert.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800608 require_str: If True, value must be a str.
Jisi Liu46e8ff62015-10-05 11:59:43 -0700609
610 Returns:
611 The bool parsed.
612
613 Raises:
614 ParseError: If a boolean value couldn't be consumed.
615 """
Feng Xiaoe841bac2015-12-11 17:09:20 -0800616 if require_str:
Jisi Liu46e8ff62015-10-05 11:59:43 -0700617 if value == 'true':
618 return True
619 elif value == 'false':
620 return False
621 else:
Feng Xiaoe841bac2015-12-11 17:09:20 -0800622 raise ParseError('Expected "true" or "false", not {0}.'.format(value))
Jisi Liu46e8ff62015-10-05 11:59:43 -0700623
624 if not isinstance(value, bool):
625 raise ParseError('Expected true or false without quotes.')
626 return value
CH Albach5477f8c2016-01-29 18:10:50 -0800627
628_WKTJSONMETHODS = {
629 'google.protobuf.Any': [_AnyMessageToJsonObject,
630 _ConvertAnyMessage],
631 'google.protobuf.Duration': [_GenericMessageToJsonObject,
632 _ConvertGenericMessage],
633 'google.protobuf.FieldMask': [_GenericMessageToJsonObject,
634 _ConvertGenericMessage],
635 'google.protobuf.ListValue': [_ListValueMessageToJsonObject,
636 _ConvertListValueMessage],
637 'google.protobuf.Struct': [_StructMessageToJsonObject,
638 _ConvertStructMessage],
639 'google.protobuf.Timestamp': [_GenericMessageToJsonObject,
640 _ConvertGenericMessage],
641 'google.protobuf.Value': [_ValueMessageToJsonObject,
642 _ConvertValueMessage]
643}