json_format.py 23 KB

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