json_format.py 24 KB

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