json_format.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. # 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. """Contains routines for printing protocol messages in JSON format.
  31. Simple usage example:
  32. # Create a proto object and serialize it to a json format string.
  33. message = my_proto_pb2.MyMessage(foo='bar')
  34. json_string = json_format.MessageToJson(message)
  35. # Parse a json format string to proto object.
  36. message = json_format.Parse(json_string, my_proto_pb2.MyMessage())
  37. """
  38. __author__ = 'jieluo@google.com (Jie Luo)'
  39. try:
  40. from collections import OrderedDict
  41. except ImportError:
  42. from ordereddict import OrderedDict #PY26
  43. import base64
  44. import json
  45. import math
  46. import six
  47. import sys
  48. from google.protobuf import descriptor
  49. from google.protobuf import symbol_database
  50. _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
  51. _INT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT32,
  52. descriptor.FieldDescriptor.CPPTYPE_UINT32,
  53. descriptor.FieldDescriptor.CPPTYPE_INT64,
  54. descriptor.FieldDescriptor.CPPTYPE_UINT64])
  55. _INT64_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT64,
  56. descriptor.FieldDescriptor.CPPTYPE_UINT64])
  57. _FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  58. descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
  59. _INFINITY = 'Infinity'
  60. _NEG_INFINITY = '-Infinity'
  61. _NAN = 'NaN'
  62. class Error(Exception):
  63. """Top-level module error for json_format."""
  64. class SerializeToJsonError(Error):
  65. """Thrown if serialization to JSON fails."""
  66. class ParseError(Error):
  67. """Thrown in case of parsing error."""
  68. def MessageToJson(message, including_default_value_fields=False):
  69. """Converts protobuf message to JSON format.
  70. Args:
  71. message: The protocol buffers message instance to serialize.
  72. including_default_value_fields: If True, singular primitive fields,
  73. repeated fields, and map fields will always be serialized. If
  74. False, only serialize non-empty fields. Singular message fields
  75. and oneof fields are not affected by this option.
  76. Returns:
  77. A string containing the JSON formatted protocol buffer message.
  78. """
  79. js = _MessageToJsonObject(message, including_default_value_fields)
  80. return json.dumps(js, indent=2)
  81. def _MessageToJsonObject(message, including_default_value_fields):
  82. """Converts message to an object according to Proto3 JSON Specification."""
  83. message_descriptor = message.DESCRIPTOR
  84. full_name = message_descriptor.full_name
  85. if _IsWrapperMessage(message_descriptor):
  86. return _WrapperMessageToJsonObject(message)
  87. if full_name in _WKTJSONMETHODS:
  88. return _WKTJSONMETHODS[full_name][0](
  89. message, including_default_value_fields)
  90. js = {}
  91. return _RegularMessageToJsonObject(
  92. message, js, including_default_value_fields)
  93. def _IsMapEntry(field):
  94. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  95. field.message_type.has_options and
  96. field.message_type.GetOptions().map_entry)
  97. def _RegularMessageToJsonObject(message, js, including_default_value_fields):
  98. """Converts normal message according to Proto3 JSON Specification."""
  99. fields = message.ListFields()
  100. include_default = including_default_value_fields
  101. try:
  102. for field, value in fields:
  103. name = field.camelcase_name
  104. if _IsMapEntry(field):
  105. # Convert a map field.
  106. v_field = field.message_type.fields_by_name['value']
  107. js_map = {}
  108. for key in value:
  109. if isinstance(key, bool):
  110. if key:
  111. recorded_key = 'true'
  112. else:
  113. recorded_key = 'false'
  114. else:
  115. recorded_key = key
  116. js_map[recorded_key] = _FieldToJsonObject(
  117. v_field, value[key], including_default_value_fields)
  118. js[name] = js_map
  119. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  120. # Convert a repeated field.
  121. js[name] = [_FieldToJsonObject(field, k, include_default)
  122. for k in value]
  123. else:
  124. js[name] = _FieldToJsonObject(field, value, include_default)
  125. # Serialize default value if including_default_value_fields is True.
  126. if including_default_value_fields:
  127. message_descriptor = message.DESCRIPTOR
  128. for field in message_descriptor.fields:
  129. # Singular message fields and oneof fields will not be affected.
  130. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and
  131. field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or
  132. field.containing_oneof):
  133. continue
  134. name = field.camelcase_name
  135. if name in js:
  136. # Skip the field which has been serailized already.
  137. continue
  138. if _IsMapEntry(field):
  139. js[name] = {}
  140. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  141. js[name] = []
  142. else:
  143. js[name] = _FieldToJsonObject(field, field.default_value)
  144. except ValueError as e:
  145. raise SerializeToJsonError(
  146. 'Failed to serialize {0} field: {1}.'.format(field.name, e))
  147. return js
  148. def _FieldToJsonObject(
  149. field, value, including_default_value_fields=False):
  150. """Converts field value according to Proto3 JSON Specification."""
  151. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  152. return _MessageToJsonObject(value, including_default_value_fields)
  153. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  154. enum_value = field.enum_type.values_by_number.get(value, None)
  155. if enum_value is not None:
  156. return enum_value.name
  157. else:
  158. raise SerializeToJsonError('Enum field contains an integer value '
  159. 'which can not mapped to an enum value.')
  160. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  161. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  162. # Use base64 Data encoding for bytes
  163. return base64.b64encode(value).decode('utf-8')
  164. else:
  165. return value
  166. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  167. return bool(value)
  168. elif field.cpp_type in _INT64_TYPES:
  169. return str(value)
  170. elif field.cpp_type in _FLOAT_TYPES:
  171. if math.isinf(value):
  172. if value < 0.0:
  173. return _NEG_INFINITY
  174. else:
  175. return _INFINITY
  176. if math.isnan(value):
  177. return _NAN
  178. return value
  179. def _AnyMessageToJsonObject(message, including_default):
  180. """Converts Any message according to Proto3 JSON Specification."""
  181. if not message.ListFields():
  182. return {}
  183. # Must print @type first, use OrderedDict instead of {}
  184. js = OrderedDict()
  185. type_url = message.type_url
  186. js['@type'] = type_url
  187. sub_message = _CreateMessageFromTypeUrl(type_url)
  188. sub_message.ParseFromString(message.value)
  189. message_descriptor = sub_message.DESCRIPTOR
  190. full_name = message_descriptor.full_name
  191. if _IsWrapperMessage(message_descriptor):
  192. js['value'] = _WrapperMessageToJsonObject(sub_message)
  193. return js
  194. if full_name in _WKTJSONMETHODS:
  195. js['value'] = _WKTJSONMETHODS[full_name][0](sub_message, including_default)
  196. return js
  197. return _RegularMessageToJsonObject(sub_message, js, including_default)
  198. def _CreateMessageFromTypeUrl(type_url):
  199. # TODO(jieluo): Should add a way that users can register the type resolver
  200. # instead of the default one.
  201. db = symbol_database.Default()
  202. type_name = type_url.split('/')[-1]
  203. try:
  204. message_descriptor = db.pool.FindMessageTypeByName(type_name)
  205. except KeyError:
  206. raise TypeError(
  207. 'Can not find message descriptor by type_url: {0}.'.format(type_url))
  208. message_class = db.GetPrototype(message_descriptor)
  209. return message_class()
  210. def _GenericMessageToJsonObject(message, unused_including_default):
  211. """Converts message by ToJsonString according to Proto3 JSON Specification."""
  212. # Duration, Timestamp and FieldMask have ToJsonString method to do the
  213. # convert. Users can also call the method directly.
  214. return message.ToJsonString()
  215. def _ValueMessageToJsonObject(message, unused_including_default=False):
  216. """Converts Value message according to Proto3 JSON Specification."""
  217. which = message.WhichOneof('kind')
  218. # If the Value message is not set treat as null_value when serialize
  219. # to JSON. The parse back result will be different from original message.
  220. if which is None or which == 'null_value':
  221. return None
  222. if which == 'list_value':
  223. return _ListValueMessageToJsonObject(message.list_value)
  224. if which == 'struct_value':
  225. value = message.struct_value
  226. else:
  227. value = getattr(message, which)
  228. oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
  229. return _FieldToJsonObject(oneof_descriptor, value)
  230. def _ListValueMessageToJsonObject(message, unused_including_default=False):
  231. """Converts ListValue message according to Proto3 JSON Specification."""
  232. return [_ValueMessageToJsonObject(value)
  233. for value in message.values]
  234. def _StructMessageToJsonObject(message, unused_including_default=False):
  235. """Converts Struct message according to Proto3 JSON Specification."""
  236. fields = message.fields
  237. ret = {}
  238. for key in fields:
  239. ret[key] = _ValueMessageToJsonObject(fields[key])
  240. return ret
  241. def _IsWrapperMessage(message_descriptor):
  242. return message_descriptor.file.name == 'google/protobuf/wrappers.proto'
  243. def _WrapperMessageToJsonObject(message):
  244. return _FieldToJsonObject(
  245. message.DESCRIPTOR.fields_by_name['value'], message.value)
  246. def _DuplicateChecker(js):
  247. result = {}
  248. for name, value in js:
  249. if name in result:
  250. raise ParseError('Failed to load JSON: duplicate key {0}.'.format(name))
  251. result[name] = value
  252. return result
  253. def Parse(text, message):
  254. """Parses a JSON representation of a protocol message into a message.
  255. Args:
  256. text: Message JSON representation.
  257. message: A protocol beffer message to merge into.
  258. Returns:
  259. The same message passed as argument.
  260. Raises::
  261. ParseError: On JSON parsing problems.
  262. """
  263. if not isinstance(text, six.text_type): text = text.decode('utf-8')
  264. try:
  265. if sys.version_info < (2, 7):
  266. # object_pair_hook is not supported before python2.7
  267. js = json.loads(text)
  268. else:
  269. js = json.loads(text, object_pairs_hook=_DuplicateChecker)
  270. except ValueError as e:
  271. raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
  272. _ConvertMessage(js, message)
  273. return message
  274. def _ConvertFieldValuePair(js, message):
  275. """Convert field value pairs into regular message.
  276. Args:
  277. js: A JSON object to convert the field value pairs.
  278. message: A regular protocol message to record the data.
  279. Raises:
  280. ParseError: In case of problems converting.
  281. """
  282. names = []
  283. message_descriptor = message.DESCRIPTOR
  284. for name in js:
  285. try:
  286. field = message_descriptor.fields_by_camelcase_name.get(name, None)
  287. if not field:
  288. raise ParseError(
  289. 'Message type "{0}" has no field named "{1}".'.format(
  290. message_descriptor.full_name, name))
  291. if name in names:
  292. raise ParseError(
  293. 'Message type "{0}" should not have multiple "{1}" fields.'.format(
  294. message.DESCRIPTOR.full_name, name))
  295. names.append(name)
  296. # Check no other oneof field is parsed.
  297. if field.containing_oneof is not None:
  298. oneof_name = field.containing_oneof.name
  299. if oneof_name in names:
  300. raise ParseError('Message type "{0}" should not have multiple "{1}" '
  301. 'oneof fields.'.format(
  302. message.DESCRIPTOR.full_name, oneof_name))
  303. names.append(oneof_name)
  304. value = js[name]
  305. if value is None:
  306. message.ClearField(field.name)
  307. continue
  308. # Parse field value.
  309. if _IsMapEntry(field):
  310. message.ClearField(field.name)
  311. _ConvertMapFieldValue(value, message, field)
  312. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  313. message.ClearField(field.name)
  314. if not isinstance(value, list):
  315. raise ParseError('repeated field {0} must be in [] which is '
  316. '{1}.'.format(name, value))
  317. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  318. # Repeated message field.
  319. for item in value:
  320. sub_message = getattr(message, field.name).add()
  321. # None is a null_value in Value.
  322. if (item is None and
  323. sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):
  324. raise ParseError('null is not allowed to be used as an element'
  325. ' in a repeated field.')
  326. _ConvertMessage(item, sub_message)
  327. else:
  328. # Repeated scalar field.
  329. for item in value:
  330. if item is None:
  331. raise ParseError('null is not allowed to be used as an element'
  332. ' in a repeated field.')
  333. getattr(message, field.name).append(
  334. _ConvertScalarFieldValue(item, field))
  335. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  336. sub_message = getattr(message, field.name)
  337. _ConvertMessage(value, sub_message)
  338. else:
  339. setattr(message, field.name, _ConvertScalarFieldValue(value, field))
  340. except ParseError as e:
  341. if field and field.containing_oneof is None:
  342. raise ParseError('Failed to parse {0} field: {1}'.format(name, e))
  343. else:
  344. raise ParseError(str(e))
  345. except ValueError as e:
  346. raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
  347. except TypeError as e:
  348. raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
  349. def _ConvertMessage(value, message):
  350. """Convert a JSON object into a message.
  351. Args:
  352. value: A JSON object.
  353. message: A WKT or regular protocol message to record the data.
  354. Raises:
  355. ParseError: In case of convert problems.
  356. """
  357. message_descriptor = message.DESCRIPTOR
  358. full_name = message_descriptor.full_name
  359. if _IsWrapperMessage(message_descriptor):
  360. _ConvertWrapperMessage(value, message)
  361. elif full_name in _WKTJSONMETHODS:
  362. _WKTJSONMETHODS[full_name][1](value, message)
  363. else:
  364. _ConvertFieldValuePair(value, message)
  365. def _ConvertAnyMessage(value, message):
  366. """Convert a JSON representation into Any message."""
  367. if isinstance(value, dict) and not value:
  368. return
  369. try:
  370. type_url = value['@type']
  371. except KeyError:
  372. raise ParseError('@type is missing when parsing any message.')
  373. sub_message = _CreateMessageFromTypeUrl(type_url)
  374. message_descriptor = sub_message.DESCRIPTOR
  375. full_name = message_descriptor.full_name
  376. if _IsWrapperMessage(message_descriptor):
  377. _ConvertWrapperMessage(value['value'], sub_message)
  378. elif full_name in _WKTJSONMETHODS:
  379. _WKTJSONMETHODS[full_name][1](value['value'], sub_message)
  380. else:
  381. del value['@type']
  382. _ConvertFieldValuePair(value, sub_message)
  383. # Sets Any message
  384. message.value = sub_message.SerializeToString()
  385. message.type_url = type_url
  386. def _ConvertGenericMessage(value, message):
  387. """Convert a JSON representation into message with FromJsonString."""
  388. # Durantion, Timestamp, FieldMask have FromJsonString method to do the
  389. # convert. Users can also call the method directly.
  390. message.FromJsonString(value)
  391. _INT_OR_FLOAT = six.integer_types + (float,)
  392. def _ConvertValueMessage(value, message):
  393. """Convert a JSON representation into Value message."""
  394. if isinstance(value, dict):
  395. _ConvertStructMessage(value, message.struct_value)
  396. elif isinstance(value, list):
  397. _ConvertListValueMessage(value, message.list_value)
  398. elif value is None:
  399. message.null_value = 0
  400. elif isinstance(value, bool):
  401. message.bool_value = value
  402. elif isinstance(value, six.string_types):
  403. message.string_value = value
  404. elif isinstance(value, _INT_OR_FLOAT):
  405. message.number_value = value
  406. else:
  407. raise ParseError('Unexpected type for Value message.')
  408. def _ConvertListValueMessage(value, message):
  409. """Convert a JSON representation into ListValue message."""
  410. if not isinstance(value, list):
  411. raise ParseError(
  412. 'ListValue must be in [] which is {0}.'.format(value))
  413. message.ClearField('values')
  414. for item in value:
  415. _ConvertValueMessage(item, message.values.add())
  416. def _ConvertStructMessage(value, message):
  417. """Convert a JSON representation into Struct message."""
  418. if not isinstance(value, dict):
  419. raise ParseError(
  420. 'Struct must be in a dict which is {0}.'.format(value))
  421. for key in value:
  422. _ConvertValueMessage(value[key], message.fields[key])
  423. return
  424. def _ConvertWrapperMessage(value, message):
  425. """Convert a JSON representation into Wrapper message."""
  426. field = message.DESCRIPTOR.fields_by_name['value']
  427. setattr(message, 'value', _ConvertScalarFieldValue(value, field))
  428. def _ConvertMapFieldValue(value, message, field):
  429. """Convert map field value for a message map field.
  430. Args:
  431. value: A JSON object to convert the map field value.
  432. message: A protocol message to record the converted data.
  433. field: The descriptor of the map field to be converted.
  434. Raises:
  435. ParseError: In case of convert problems.
  436. """
  437. if not isinstance(value, dict):
  438. raise ParseError(
  439. 'Map field {0} must be in a dict which is {1}.'.format(
  440. field.name, value))
  441. key_field = field.message_type.fields_by_name['key']
  442. value_field = field.message_type.fields_by_name['value']
  443. for key in value:
  444. key_value = _ConvertScalarFieldValue(key, key_field, True)
  445. if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  446. _ConvertMessage(value[key], getattr(message, field.name)[key_value])
  447. else:
  448. getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(
  449. value[key], value_field)
  450. def _ConvertScalarFieldValue(value, field, require_str=False):
  451. """Convert a single scalar field value.
  452. Args:
  453. value: A scalar value to convert the scalar field value.
  454. field: The descriptor of the field to convert.
  455. require_str: If True, the field value must be a str.
  456. Returns:
  457. The converted scalar field value
  458. Raises:
  459. ParseError: In case of convert problems.
  460. """
  461. if field.cpp_type in _INT_TYPES:
  462. return _ConvertInteger(value)
  463. elif field.cpp_type in _FLOAT_TYPES:
  464. return _ConvertFloat(value)
  465. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  466. return _ConvertBool(value, require_str)
  467. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  468. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  469. return base64.b64decode(value)
  470. else:
  471. return value
  472. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  473. # Convert an enum value.
  474. enum_value = field.enum_type.values_by_name.get(value, None)
  475. if enum_value is None:
  476. raise ParseError(
  477. 'Enum value must be a string literal with double quotes. '
  478. 'Type "{0}" has no value named {1}.'.format(
  479. field.enum_type.full_name, value))
  480. return enum_value.number
  481. def _ConvertInteger(value):
  482. """Convert an integer.
  483. Args:
  484. value: A scalar value to convert.
  485. Returns:
  486. The integer value.
  487. Raises:
  488. ParseError: If an integer couldn't be consumed.
  489. """
  490. if isinstance(value, float):
  491. raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
  492. if isinstance(value, six.text_type) and value.find(' ') != -1:
  493. raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
  494. return int(value)
  495. def _ConvertFloat(value):
  496. """Convert an floating point number."""
  497. if value == 'nan':
  498. raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
  499. try:
  500. # Assume Python compatible syntax.
  501. return float(value)
  502. except ValueError:
  503. # Check alternative spellings.
  504. if value == _NEG_INFINITY:
  505. return float('-inf')
  506. elif value == _INFINITY:
  507. return float('inf')
  508. elif value == _NAN:
  509. return float('nan')
  510. else:
  511. raise ParseError('Couldn\'t parse float: {0}.'.format(value))
  512. def _ConvertBool(value, require_str):
  513. """Convert a boolean value.
  514. Args:
  515. value: A scalar value to convert.
  516. require_str: If True, value must be a str.
  517. Returns:
  518. The bool parsed.
  519. Raises:
  520. ParseError: If a boolean value couldn't be consumed.
  521. """
  522. if require_str:
  523. if value == 'true':
  524. return True
  525. elif value == 'false':
  526. return False
  527. else:
  528. raise ParseError('Expected "true" or "false", not {0}.'.format(value))
  529. if not isinstance(value, bool):
  530. raise ParseError('Expected true or false without quotes.')
  531. return value
  532. _WKTJSONMETHODS = {
  533. 'google.protobuf.Any': [_AnyMessageToJsonObject,
  534. _ConvertAnyMessage],
  535. 'google.protobuf.Duration': [_GenericMessageToJsonObject,
  536. _ConvertGenericMessage],
  537. 'google.protobuf.FieldMask': [_GenericMessageToJsonObject,
  538. _ConvertGenericMessage],
  539. 'google.protobuf.ListValue': [_ListValueMessageToJsonObject,
  540. _ConvertListValueMessage],
  541. 'google.protobuf.Struct': [_StructMessageToJsonObject,
  542. _ConvertStructMessage],
  543. 'google.protobuf.Timestamp': [_GenericMessageToJsonObject,
  544. _ConvertGenericMessage],
  545. 'google.protobuf.Value': [_ValueMessageToJsonObject,
  546. _ConvertValueMessage]
  547. }