json_format.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Contains routines for printing protocol messages in JSON format.
  8. Simple usage example:
  9. # Create a proto object and serialize it to a json format string.
  10. message = my_proto_pb2.MyMessage(foo='bar')
  11. json_string = json_format.MessageToJson(message)
  12. # Parse a json format string to proto object.
  13. message = json_format.Parse(json_string, my_proto_pb2.MyMessage())
  14. """
  15. __author__ = 'jieluo@google.com (Jie Luo)'
  16. import base64
  17. from collections import OrderedDict
  18. import json
  19. import math
  20. from operator import methodcaller
  21. import re
  22. from google.protobuf import descriptor
  23. from google.protobuf import descriptor_pool
  24. from google.protobuf import message_factory
  25. from google.protobuf import symbol_database
  26. from google.protobuf.internal import type_checkers
  27. _INT_TYPES = frozenset([
  28. descriptor.FieldDescriptor.CPPTYPE_INT32,
  29. descriptor.FieldDescriptor.CPPTYPE_UINT32,
  30. descriptor.FieldDescriptor.CPPTYPE_INT64,
  31. descriptor.FieldDescriptor.CPPTYPE_UINT64,
  32. ])
  33. _INT64_TYPES = frozenset([
  34. descriptor.FieldDescriptor.CPPTYPE_INT64,
  35. descriptor.FieldDescriptor.CPPTYPE_UINT64,
  36. ])
  37. _FLOAT_TYPES = frozenset([
  38. descriptor.FieldDescriptor.CPPTYPE_FLOAT,
  39. descriptor.FieldDescriptor.CPPTYPE_DOUBLE,
  40. ])
  41. _INFINITY = 'Infinity'
  42. _NEG_INFINITY = '-Infinity'
  43. _NAN = 'NaN'
  44. _UNPAIRED_SURROGATE_PATTERN = re.compile(
  45. '[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]'
  46. )
  47. _VALID_EXTENSION_NAME = re.compile(r'\[[a-zA-Z0-9\._]*\]$')
  48. class Error(Exception):
  49. """Top-level module error for json_format."""
  50. class SerializeToJsonError(Error):
  51. """Thrown if serialization to JSON fails."""
  52. class ParseError(Error):
  53. """Thrown in case of parsing error."""
  54. class EnumStringValueParseError(ParseError):
  55. """Thrown if unknown string enum value is encountered.
  56. This exception is suppressed if ignore_unknown_fields is set.
  57. """
  58. def MessageToJson(
  59. message,
  60. preserving_proto_field_name=False,
  61. indent=2,
  62. sort_keys=False,
  63. use_integers_for_enums=False,
  64. descriptor_pool=None,
  65. ensure_ascii=True,
  66. always_print_fields_with_no_presence=False,
  67. *,
  68. unquote_int64_if_possible=False,
  69. ):
  70. """Converts protobuf message to JSON format.
  71. Args:
  72. message: The protocol buffers message instance to serialize.
  73. always_print_fields_with_no_presence: If True, fields without presence
  74. (implicit presence scalars, repeated fields, and map fields) will always
  75. be serialized. Any field that supports presence is not affected by this
  76. option (including singular message fields and oneof fields).
  77. preserving_proto_field_name: If True, use the original proto field names as
  78. defined in the .proto file. If False, convert the field names to
  79. lowerCamelCase.
  80. indent: The JSON object will be pretty-printed with this indent level. An
  81. indent level of 0 or negative will only insert newlines. If the indent
  82. level is None, no newlines will be inserted.
  83. sort_keys: If True, then the output will be sorted by field names.
  84. use_integers_for_enums: If true, print integers instead of enum names.
  85. descriptor_pool: A Descriptor Pool for resolving types. If None use the
  86. default.
  87. ensure_ascii: If True, strings with non-ASCII characters are escaped. If
  88. False, Unicode strings are returned unchanged.
  89. unquote_int64_if_possible: If True, unquote int64 fields for values that are
  90. safe to emit as numbers (all values smaller than 2^53 and a sparse set of
  91. values that are larger).
  92. Returns:
  93. A string containing the JSON formatted protocol buffer message.
  94. """
  95. printer = _Printer(
  96. preserving_proto_field_name,
  97. use_integers_for_enums,
  98. descriptor_pool,
  99. always_print_fields_with_no_presence,
  100. unquote_int64_if_possible=unquote_int64_if_possible,
  101. )
  102. return printer.ToJsonString(message, indent, sort_keys, ensure_ascii)
  103. def MessageToDict(
  104. message,
  105. always_print_fields_with_no_presence=False,
  106. preserving_proto_field_name=False,
  107. use_integers_for_enums=False,
  108. descriptor_pool=None,
  109. *,
  110. unquote_int64_if_possible=False,
  111. ):
  112. """Converts protobuf message to a dictionary.
  113. When the dictionary is encoded to JSON, it conforms to ProtoJSON spec.
  114. Args:
  115. message: The protocol buffers message instance to serialize.
  116. always_print_fields_with_no_presence: If True, fields without presence
  117. (implicit presence scalars, repeated fields, and map fields) will always
  118. be serialized. Any field that supports presence is not affected by this
  119. option (including singular message fields and oneof fields).
  120. preserving_proto_field_name: If True, use the original proto field names as
  121. defined in the .proto file. If False, convert the field names to
  122. lowerCamelCase.
  123. use_integers_for_enums: If true, print integers instead of enum names.
  124. descriptor_pool: A Descriptor Pool for resolving types. If None use the
  125. default.
  126. unquote_int64_if_possible: If True, unquote int64 fields for values that are
  127. safe to emit as numbers (all values smaller than 2^53 and a sparse set of
  128. values that are larger).
  129. Returns:
  130. A dict representation of the protocol buffer message.
  131. """
  132. printer = _Printer(
  133. preserving_proto_field_name,
  134. use_integers_for_enums,
  135. descriptor_pool,
  136. always_print_fields_with_no_presence,
  137. unquote_int64_if_possible=unquote_int64_if_possible,
  138. )
  139. # pylint: disable=protected-access
  140. return printer._MessageToJsonObject(message)
  141. def _IsMapEntry(field):
  142. return (
  143. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  144. and field.message_type.has_options
  145. and field.message_type.GetOptions().map_entry
  146. )
  147. class _Printer(object):
  148. """JSON format printer for protocol message."""
  149. def __init__(
  150. self,
  151. preserving_proto_field_name=False,
  152. use_integers_for_enums=False,
  153. descriptor_pool=None,
  154. always_print_fields_with_no_presence=False,
  155. *,
  156. unquote_int64_if_possible=False,
  157. ):
  158. self.always_print_fields_with_no_presence = (
  159. always_print_fields_with_no_presence
  160. )
  161. self.preserving_proto_field_name = preserving_proto_field_name
  162. self.use_integers_for_enums = use_integers_for_enums
  163. self.descriptor_pool = descriptor_pool
  164. self.unquote_int64_if_possible = unquote_int64_if_possible
  165. self._enumvalue_json_extension = None
  166. def _GetEnumValueJsonExtension(self):
  167. if self._enumvalue_json_extension is None:
  168. # Options are always put on the default pool, so we only search the
  169. # default pool.
  170. try:
  171. # Using reflection to FindExtensionByName is quite expensive, hence the
  172. # gymnastics to cache it into the instance attribute
  173. # _enumvalue_json_extension.
  174. # TODO: b/551998570 - Over the longer term, we can consider putting this
  175. # information in bootstrap files so that we don't have to rely on using
  176. # reflection to perform this lookup at all.
  177. self._enumvalue_json_extension = (
  178. descriptor_pool.Default().FindExtensionByName('pb.enumvalue.json')
  179. )
  180. except KeyError:
  181. self._enumvalue_json_extension = {}
  182. return self._enumvalue_json_extension or None
  183. def _GetJsonEnumValueOption(self, ev):
  184. """Helper to get the JsonEnumValueOptions for an enum value."""
  185. extension_descriptor = self._GetEnumValueJsonExtension()
  186. if extension_descriptor is None:
  187. return None
  188. return _GetJsonEnumValueOption(ev, extension_descriptor)
  189. def ToJsonString(self, message, indent, sort_keys, ensure_ascii):
  190. js = self._MessageToJsonObject(message)
  191. return json.dumps(
  192. js, indent=indent, sort_keys=sort_keys, ensure_ascii=ensure_ascii
  193. )
  194. def _MessageToJsonObject(self, message):
  195. """Converts message to an object according to ProtoJSON Specification."""
  196. message_descriptor = message.DESCRIPTOR
  197. full_name = message_descriptor.full_name
  198. if _IsWrapperMessage(message_descriptor):
  199. return self._WrapperMessageToJsonObject(message)
  200. if full_name in _WKTJSONMETHODS:
  201. return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
  202. js = {}
  203. return self._RegularMessageToJsonObject(message, js)
  204. def _RegularMessageToJsonObject(self, message, js):
  205. """Converts normal message according to ProtoJSON Specification."""
  206. fields = message.ListFields()
  207. try:
  208. for field, value in fields:
  209. if field.is_extension:
  210. name = '[%s]' % field.full_name
  211. elif self.preserving_proto_field_name:
  212. name = field.name
  213. else:
  214. name = field.json_name
  215. if _IsMapEntry(field):
  216. # Convert a map field.
  217. v_field = field.message_type.fields_by_name['value']
  218. js_map = {}
  219. for key in value:
  220. if isinstance(key, bool):
  221. if key:
  222. recorded_key = 'true'
  223. else:
  224. recorded_key = 'false'
  225. else:
  226. recorded_key = str(key)
  227. js_map[recorded_key] = self._FieldToJsonObject(v_field, value[key])
  228. js[name] = js_map
  229. elif field.is_repeated:
  230. # Convert a repeated field.
  231. js[name] = [self._FieldToJsonObject(field, k) for k in value]
  232. else:
  233. js[name] = self._FieldToJsonObject(field, value)
  234. # Serialize default value if including_default_value_fields is True.
  235. if (
  236. self.always_print_fields_with_no_presence
  237. ):
  238. message_descriptor = message.DESCRIPTOR
  239. for field in message_descriptor.fields:
  240. # always_print_fields_with_no_presence doesn't apply to
  241. # any field which supports presence.
  242. if self.always_print_fields_with_no_presence and field.has_presence:
  243. continue
  244. if self.preserving_proto_field_name:
  245. name = field.name
  246. else:
  247. name = field.json_name
  248. if name in js:
  249. # Skip the field which has been serialized already.
  250. continue
  251. if _IsMapEntry(field):
  252. js[name] = {}
  253. elif field.is_repeated:
  254. js[name] = []
  255. else:
  256. js[name] = self._FieldToJsonObject(field, field.default_value)
  257. except ValueError as e:
  258. raise SerializeToJsonError(
  259. 'Failed to serialize {0} field: {1}.'.format(field.name, e)
  260. ) from e
  261. return js
  262. def _FieldToJsonObject(self, field, value):
  263. """Converts field value according to ProtoJSON Specification."""
  264. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  265. return self._MessageToJsonObject(value)
  266. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  267. if self.use_integers_for_enums:
  268. return value
  269. if field.enum_type.full_name == 'google.protobuf.NullValue':
  270. return None
  271. enum_value = field.enum_type.values_by_number.get(value, None)
  272. if enum_value is not None:
  273. option = self._GetJsonEnumValueOption(enum_value)
  274. if option is not None:
  275. return option.string
  276. return enum_value.name
  277. else:
  278. if field.enum_type.is_closed:
  279. raise SerializeToJsonError(
  280. 'Enum field contains an integer value '
  281. 'which can not mapped to an enum value.'
  282. )
  283. else:
  284. return value
  285. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  286. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  287. # Use base64 Data encoding for bytes
  288. return base64.b64encode(value).decode('utf-8')
  289. else:
  290. return str(value)
  291. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  292. return bool(value)
  293. elif field.cpp_type in _INT64_TYPES:
  294. if self.unquote_int64_if_possible and float(value) == value:
  295. return value
  296. else:
  297. return str(value)
  298. elif field.cpp_type in _FLOAT_TYPES:
  299. if math.isinf(value):
  300. if value < 0.0:
  301. return _NEG_INFINITY
  302. else:
  303. return _INFINITY
  304. if math.isnan(value):
  305. return _NAN
  306. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
  307. return type_checkers.ToShortestFloat(value)
  308. return value
  309. def _AnyMessageToJsonObject(self, message):
  310. """Converts Any message according to ProtoJSON Specification."""
  311. if not message.ListFields():
  312. return {}
  313. # Must print @type first, use OrderedDict instead of {}
  314. js = OrderedDict()
  315. type_url = message.type_url
  316. js['@type'] = type_url
  317. sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool)
  318. sub_message.ParseFromString(message.value)
  319. message_descriptor = sub_message.DESCRIPTOR
  320. full_name = message_descriptor.full_name
  321. if _IsWrapperMessage(message_descriptor):
  322. js['value'] = self._WrapperMessageToJsonObject(sub_message)
  323. return js
  324. if full_name in _WKTJSONMETHODS:
  325. js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0], sub_message)(
  326. self
  327. )
  328. return js
  329. return self._RegularMessageToJsonObject(sub_message, js)
  330. def _GenericMessageToJsonObject(self, message):
  331. """Converts message according to ProtoJSON Specification."""
  332. # Duration, Timestamp and FieldMask have ToJsonString method to do the
  333. # convert. Users can also call the method directly.
  334. return message.ToJsonString()
  335. def _ValueMessageToJsonObject(self, message):
  336. """Converts Value message according to ProtoJSON Specification."""
  337. which = message.WhichOneof('kind')
  338. # If the Value message is not set treat as null_value when serialize
  339. # to JSON. The parse back result will be different from original message.
  340. if which is None or which == 'null_value':
  341. return None
  342. if which == 'list_value':
  343. return self._ListValueMessageToJsonObject(message.list_value)
  344. if which == 'number_value':
  345. value = message.number_value
  346. if math.isinf(value):
  347. raise ValueError(
  348. 'Fail to serialize Infinity for Value.number_value, '
  349. 'which would parse as string_value'
  350. )
  351. if math.isnan(value):
  352. raise ValueError(
  353. 'Fail to serialize NaN for Value.number_value, '
  354. 'which would parse as string_value'
  355. )
  356. else:
  357. value = getattr(message, which)
  358. oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
  359. return self._FieldToJsonObject(oneof_descriptor, value)
  360. def _ListValueMessageToJsonObject(self, message):
  361. """Converts ListValue message according to ProtoJSON Specification."""
  362. return [self._ValueMessageToJsonObject(value) for value in message.values]
  363. def _StructMessageToJsonObject(self, message):
  364. """Converts Struct message according to ProtoJSON Specification."""
  365. fields = message.fields
  366. ret = {}
  367. for key in fields:
  368. ret[key] = self._ValueMessageToJsonObject(fields[key])
  369. return ret
  370. def _WrapperMessageToJsonObject(self, message):
  371. return self._FieldToJsonObject(
  372. message.DESCRIPTOR.fields_by_name['value'], message.value
  373. )
  374. def _IsWrapperMessage(message_descriptor):
  375. return message_descriptor.file.name == 'google/protobuf/wrappers.proto'
  376. def _DuplicateChecker(js):
  377. result = {}
  378. for name, value in js:
  379. if name in result:
  380. raise ParseError('Failed to load JSON: duplicate key {0}.'.format(name))
  381. result[name] = value
  382. return result
  383. def _CreateMessageFromTypeUrl(type_url, descriptor_pool):
  384. """Creates a message from a type URL."""
  385. db = symbol_database.Default()
  386. pool = db.pool if descriptor_pool is None else descriptor_pool
  387. type_name = type_url.split('/')[-1]
  388. try:
  389. message_descriptor = pool.FindMessageTypeByName(type_name)
  390. except KeyError as e:
  391. raise TypeError(
  392. 'Can not find message descriptor by type_url: {0}'.format(type_url)
  393. ) from e
  394. message_class = message_factory.GetMessageClass(message_descriptor)
  395. return message_class()
  396. def Parse(
  397. text,
  398. message,
  399. ignore_unknown_fields=False,
  400. descriptor_pool=None,
  401. max_recursion_depth=100,
  402. ):
  403. """Parses a JSON representation of a protocol message into a message.
  404. Args:
  405. text: Message JSON representation.
  406. message: A protocol buffer message to merge into.
  407. ignore_unknown_fields: If True, do not raise errors for unknown fields.
  408. descriptor_pool: A Descriptor Pool for resolving types. If None use the
  409. default.
  410. max_recursion_depth: max recursion depth of JSON message to be deserialized.
  411. JSON messages over this depth will fail to be deserialized. Default value
  412. is 100.
  413. Returns:
  414. The same message passed as argument.
  415. Raises::
  416. ParseError: On JSON parsing problems.
  417. """
  418. if not isinstance(text, str):
  419. text = text.decode('utf-8')
  420. try:
  421. js = json.loads(text, object_pairs_hook=_DuplicateChecker)
  422. except Exception as e:
  423. raise ParseError('Failed to load JSON: {0}.'.format(str(e))) from e
  424. try:
  425. return ParseDict(
  426. js, message, ignore_unknown_fields, descriptor_pool, max_recursion_depth
  427. )
  428. except ParseError as e:
  429. raise e
  430. except Exception as e:
  431. raise ParseError(
  432. 'Failed to parse JSON: {0}: {1}.'.format(type(e).__name__, str(e))
  433. ) from e
  434. def ParseDict(
  435. js_dict,
  436. message,
  437. ignore_unknown_fields=False,
  438. descriptor_pool=None,
  439. max_recursion_depth=100,
  440. ):
  441. """Parses a JSON dictionary representation into a message.
  442. Args:
  443. js_dict: Dict representation of a JSON message.
  444. message: A protocol buffer message to merge into.
  445. ignore_unknown_fields: If True, do not raise errors for unknown fields.
  446. descriptor_pool: A Descriptor Pool for resolving types. If None use the
  447. default.
  448. max_recursion_depth: max recursion depth of JSON message to be deserialized.
  449. JSON messages over this depth will fail to be deserialized. Default value
  450. is 100.
  451. Returns:
  452. The same message passed as argument.
  453. """
  454. parser = _Parser(ignore_unknown_fields, descriptor_pool, max_recursion_depth)
  455. parser.ConvertMessage(js_dict, message, '')
  456. return message
  457. _INT_OR_FLOAT = (int, float)
  458. _LIST_LIKE = (list, tuple)
  459. class _Parser(object):
  460. """JSON format parser for protocol message."""
  461. def __init__(
  462. self, ignore_unknown_fields, descriptor_pool, max_recursion_depth
  463. ):
  464. self.ignore_unknown_fields = ignore_unknown_fields
  465. self.descriptor_pool = descriptor_pool
  466. self.max_recursion_depth = max_recursion_depth
  467. self.recursion_depth = 0
  468. self._custom_enum_names_cache = {}
  469. self._enumvalue_json_extension = None
  470. def _GetEnumValueJsonExtension(self):
  471. if self._enumvalue_json_extension is None:
  472. # Options are always put on the default pool, so we only search the
  473. # default pool.
  474. try:
  475. self._enumvalue_json_extension = (
  476. descriptor_pool.Default().FindExtensionByName('pb.enumvalue.json')
  477. )
  478. except KeyError:
  479. self._enumvalue_json_extension = {}
  480. return self._enumvalue_json_extension or None
  481. def ConvertMessage(self, value, message, path):
  482. """Convert a JSON object into a message.
  483. Args:
  484. value: A JSON object.
  485. message: A WKT or regular protocol message to record the data.
  486. path: parent path to log parse error info.
  487. Raises:
  488. ParseError: In case of convert problems.
  489. """
  490. # Increment recursion depth at message entry. The max_recursion_depth limit
  491. # is exclusive: a depth value equal to max_recursion_depth will trigger an
  492. # error. For example, with max_recursion_depth=5, nesting up to depth 4 is
  493. # allowed, but attempting depth 5 raises ParseError.
  494. self.recursion_depth += 1
  495. if self.recursion_depth > self.max_recursion_depth:
  496. raise ParseError(
  497. 'Message too deep. Max recursion depth is {0}'.format(
  498. self.max_recursion_depth
  499. )
  500. )
  501. message_descriptor = message.DESCRIPTOR
  502. full_name = message_descriptor.full_name
  503. if not path:
  504. path = message_descriptor.name
  505. if _IsWrapperMessage(message_descriptor):
  506. self._ConvertWrapperMessage(value, message, path)
  507. elif full_name in _WKTJSONMETHODS:
  508. methodcaller(_WKTJSONMETHODS[full_name][1], value, message, path)(self)
  509. else:
  510. self._ConvertFieldValuePair(value, message, path)
  511. self.recursion_depth -= 1
  512. def _ConvertFieldValuePair(self, js, message, path):
  513. """Convert field value pairs into regular message.
  514. Args:
  515. js: A JSON object to convert the field value pairs.
  516. message: A regular protocol message to record the data.
  517. path: parent path to log parse error info.
  518. Raises:
  519. ParseError: In case of problems converting.
  520. """
  521. names = []
  522. message_descriptor = message.DESCRIPTOR
  523. fields_by_json_name = dict(
  524. (f.json_name, f) for f in message_descriptor.fields
  525. )
  526. def _ClearFieldOrExtension(message, field):
  527. if field.is_extension:
  528. message.ClearExtension(field)
  529. else:
  530. message.ClearField(field.name)
  531. def _GetFieldOrExtension(message, field):
  532. if field.is_extension:
  533. return message.Extensions[field]
  534. else:
  535. return getattr(message, field.name)
  536. def _SetFieldOrExtension(message, field, value):
  537. if field.is_extension:
  538. message.Extensions[field] = value
  539. else:
  540. setattr(message, field.name, value)
  541. for name in js:
  542. try:
  543. field = fields_by_json_name.get(name, None)
  544. if not field:
  545. field = message_descriptor.fields_by_name.get(name, None)
  546. if not field and _VALID_EXTENSION_NAME.match(name):
  547. if not message_descriptor.is_extendable:
  548. raise ParseError(
  549. 'Message type {0} does not have extensions at {1}'.format(
  550. message_descriptor.full_name, path
  551. )
  552. )
  553. identifier = name[1:-1] # strip [] brackets
  554. # pylint: disable=protected-access
  555. field = message.Extensions._FindExtensionByName(identifier)
  556. # pylint: enable=protected-access
  557. if not field:
  558. # Try looking for extension by the message type name, dropping the
  559. # field name following the final . separator in full_name.
  560. identifier = '.'.join(identifier.split('.')[:-1])
  561. # pylint: disable=protected-access
  562. field = message.Extensions._FindExtensionByName(identifier)
  563. # pylint: enable=protected-access
  564. if not field:
  565. if self.ignore_unknown_fields:
  566. continue
  567. raise ParseError(
  568. (
  569. 'Message type "{0}" has no field named "{1}" at "{2}".\n'
  570. ' Available Fields(except extensions): "{3}"'
  571. ).format(
  572. message_descriptor.full_name,
  573. name,
  574. path,
  575. [f.json_name for f in message_descriptor.fields],
  576. )
  577. )
  578. if name in names:
  579. raise ParseError(
  580. 'Message type "{0}" should not have multiple '
  581. '"{1}" fields at "{2}".'.format(
  582. message.DESCRIPTOR.full_name, name, path
  583. )
  584. )
  585. names.append(name)
  586. value = js[name]
  587. # Check no other oneof field is parsed.
  588. if field.containing_oneof is not None and value is not None:
  589. oneof_name = field.containing_oneof.name
  590. if oneof_name in names:
  591. raise ParseError(
  592. 'Message type "{0}" should not have multiple '
  593. '"{1}" oneof fields at "{2}".'.format(
  594. message.DESCRIPTOR.full_name, oneof_name, path
  595. )
  596. )
  597. names.append(oneof_name)
  598. if value is None:
  599. if (
  600. field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE
  601. and field.message_type.full_name == 'google.protobuf.Value'
  602. ):
  603. sub_message = _GetFieldOrExtension(message, field)
  604. sub_message.null_value = 0
  605. elif (
  606. field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM
  607. and field.enum_type.full_name == 'google.protobuf.NullValue'
  608. ):
  609. _SetFieldOrExtension(message, field, 0)
  610. else:
  611. _ClearFieldOrExtension(message, field)
  612. continue
  613. # Parse field value.
  614. if _IsMapEntry(field):
  615. _ClearFieldOrExtension(message, field)
  616. self._ConvertMapFieldValue(
  617. value, message, field, '{0}.{1}'.format(path, name)
  618. )
  619. elif field.is_repeated:
  620. _ClearFieldOrExtension(message, field)
  621. if not isinstance(value, _LIST_LIKE):
  622. raise ParseError(
  623. 'repeated field {0} must be in [] which is {1} at {2}'.format(
  624. name, value, path
  625. )
  626. )
  627. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  628. # Repeated message field.
  629. for index, item in enumerate(value):
  630. sub_message = _GetFieldOrExtension(message, field).add()
  631. # None is a null_value in Value.
  632. if (
  633. item is None
  634. and sub_message.DESCRIPTOR.full_name
  635. != 'google.protobuf.Value'
  636. ):
  637. raise ParseError(
  638. 'null is not allowed to be used as an element'
  639. ' in a repeated field at {0}.{1}[{2}]'.format(
  640. path, name, index
  641. )
  642. )
  643. self.ConvertMessage(
  644. item, sub_message, '{0}.{1}[{2}]'.format(path, name, index)
  645. )
  646. else:
  647. # Repeated scalar field.
  648. for index, item in enumerate(value):
  649. if item is None:
  650. raise ParseError(
  651. 'null is not allowed to be used as an element'
  652. ' in a repeated field at {0}.{1}[{2}]'.format(
  653. path, name, index
  654. )
  655. )
  656. self._ConvertAndAppendScalar(
  657. message, field, item, '{0}.{1}[{2}]'.format(path, name, index)
  658. )
  659. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  660. sub_message = _GetFieldOrExtension(message, field)
  661. sub_message.SetInParent()
  662. self.ConvertMessage(value, sub_message, '{0}.{1}'.format(path, name))
  663. else:
  664. self._ConvertAndSetScalar(
  665. message, field, value, '{0}.{1}'.format(path, name)
  666. )
  667. except ParseError as e:
  668. if field and field.containing_oneof is None:
  669. raise ParseError(
  670. 'Failed to parse {0} field: {1}.'.format(name, e)
  671. ) from e
  672. else:
  673. raise ParseError(str(e)) from e
  674. except ValueError as e:
  675. raise ParseError(
  676. 'Failed to parse {0} field: {1}.'.format(name, e)
  677. ) from e
  678. except TypeError as e:
  679. raise ParseError(
  680. 'Failed to parse {0} field: {1}.'.format(name, e)
  681. ) from e
  682. def _ConvertAnyMessage(self, value, message, path):
  683. """Convert a JSON representation into Any message."""
  684. if isinstance(value, dict) and not value:
  685. return
  686. try:
  687. type_url = value['@type']
  688. except KeyError as e:
  689. raise ParseError(
  690. '@type is missing when parsing any message at {0}'.format(path)
  691. ) from e
  692. try:
  693. sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool)
  694. except TypeError as e:
  695. raise ParseError('{0} at {1}'.format(e, path)) from e
  696. message_descriptor = sub_message.DESCRIPTOR
  697. full_name = message_descriptor.full_name
  698. if _IsWrapperMessage(message_descriptor):
  699. self._ConvertWrapperMessage(
  700. value['value'], sub_message, '{0}.value'.format(path)
  701. )
  702. elif full_name in _WKTJSONMETHODS:
  703. # For well-known types (including nested Any), use ConvertMessage
  704. # to ensure recursion depth is properly tracked
  705. self.ConvertMessage(value['value'], sub_message, '{0}.value'.format(path))
  706. else:
  707. del value['@type']
  708. try:
  709. self._ConvertFieldValuePair(value, sub_message, path)
  710. finally:
  711. value['@type'] = type_url
  712. # Sets Any message
  713. message.value = sub_message.SerializeToString()
  714. message.type_url = type_url
  715. def _ConvertGenericMessage(self, value, message, path):
  716. """Convert a JSON representation into message with FromJsonString."""
  717. # Duration, Timestamp, FieldMask have a FromJsonString method to do the
  718. # conversion. Users can also call the method directly.
  719. try:
  720. message.FromJsonString(value)
  721. except ValueError as e:
  722. raise ParseError('{0} at {1}'.format(e, path)) from e
  723. def _ConvertValueMessage(self, value, message, path):
  724. """Convert a JSON representation into Value message."""
  725. if isinstance(value, dict):
  726. self.ConvertMessage(value, message.struct_value, path)
  727. elif isinstance(value, _LIST_LIKE):
  728. self.ConvertMessage(value, message.list_value, path)
  729. elif value is None:
  730. message.null_value = 0
  731. elif isinstance(value, bool):
  732. message.bool_value = value
  733. elif isinstance(value, str):
  734. message.string_value = value
  735. elif isinstance(value, _INT_OR_FLOAT):
  736. message.number_value = value
  737. else:
  738. raise ParseError(
  739. 'Value {0} has unexpected type {1} at {2}'.format(
  740. value, type(value), path
  741. )
  742. )
  743. def _ConvertListOrTupleValueMessage(self, value, message, path):
  744. """Convert a JSON representation into ListValue message."""
  745. if not isinstance(value, _LIST_LIKE):
  746. raise ParseError(
  747. 'ListValue must be in [] which is {0} at {1}'.format(value, path)
  748. )
  749. message.ClearField('values')
  750. for index, item in enumerate(value):
  751. self.ConvertMessage(
  752. item, message.values.add(), '{0}[{1}]'.format(path, index)
  753. )
  754. def _ConvertStructMessage(self, value, message, path):
  755. """Convert a JSON representation into Struct message."""
  756. if not isinstance(value, dict):
  757. raise ParseError(
  758. 'Struct must be in a dict which is {0} at {1}'.format(value, path)
  759. )
  760. # Clear will mark the struct as modified so it will be created even if
  761. # there are no values.
  762. message.Clear()
  763. for key in value:
  764. self.ConvertMessage(
  765. value[key], message.fields[key], '{0}.{1}'.format(path, key)
  766. )
  767. return
  768. def _ConvertWrapperMessage(self, value, message, path):
  769. """Convert a JSON representation into Wrapper message."""
  770. field = message.DESCRIPTOR.fields_by_name['value']
  771. self._ConvertAndSetScalar(
  772. message, field, value, path='{0}.value'.format(path)
  773. )
  774. def _ConvertMapFieldValue(self, value, message, field, path):
  775. """Convert map field value for a message map field.
  776. Args:
  777. value: A JSON object to convert the map field value.
  778. message: A protocol message to record the converted data.
  779. field: The descriptor of the map field to be converted.
  780. path: parent path to log parse error info.
  781. Raises:
  782. ParseError: In case of convert problems.
  783. """
  784. if not isinstance(value, dict):
  785. raise ParseError(
  786. 'Map field {0} must be in a dict which is {1} at {2}'.format(
  787. field.name, value, path
  788. )
  789. )
  790. key_field = field.message_type.fields_by_name['key']
  791. value_field = field.message_type.fields_by_name['value']
  792. for key in value:
  793. key_value = _ConvertScalarFieldValue(
  794. key,
  795. key_field,
  796. '{0}.key'.format(path),
  797. self._custom_enum_names_cache,
  798. self._GetEnumValueJsonExtension(),
  799. require_str=True,
  800. )
  801. if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  802. self.ConvertMessage(
  803. value[key],
  804. getattr(message, field.name)[key_value],
  805. '{0}[{1}]'.format(path, key_value),
  806. )
  807. else:
  808. self._ConvertAndSetScalarToMapKey(
  809. message,
  810. field,
  811. key_value,
  812. value[key],
  813. path='{0}[{1}]'.format(path, key_value),
  814. )
  815. def _ConvertAndSetScalar(self, message, field, js_value, path):
  816. """Convert scalar from js_value and assign it to message.field."""
  817. try:
  818. value = _ConvertScalarFieldValue(
  819. js_value,
  820. field,
  821. path,
  822. self._custom_enum_names_cache,
  823. self._GetEnumValueJsonExtension(),
  824. )
  825. if field.is_extension:
  826. message.Extensions[field] = value
  827. else:
  828. setattr(message, field.name, value)
  829. except EnumStringValueParseError:
  830. if not self.ignore_unknown_fields:
  831. raise
  832. def _ConvertAndAppendScalar(self, message, repeated_field, js_value, path):
  833. """Convert scalar from js_value and append it to message.repeated_field."""
  834. try:
  835. if repeated_field.is_extension:
  836. repeated = message.Extensions[repeated_field]
  837. else:
  838. repeated = getattr(message, repeated_field.name)
  839. value = _ConvertScalarFieldValue(
  840. js_value,
  841. repeated_field,
  842. path,
  843. self._custom_enum_names_cache,
  844. self._GetEnumValueJsonExtension(),
  845. )
  846. repeated.append(value)
  847. except EnumStringValueParseError:
  848. if not self.ignore_unknown_fields:
  849. raise
  850. def _ConvertAndSetScalarToMapKey(
  851. self, message, map_field, converted_key, js_value, path
  852. ):
  853. """Convert scalar from 'js_value' and add it to message.map_field[converted_key]."""
  854. try:
  855. getattr(message, map_field.name)[converted_key] = (
  856. _ConvertScalarFieldValue(
  857. js_value,
  858. map_field.message_type.fields_by_name['value'],
  859. path,
  860. self._custom_enum_names_cache,
  861. self._GetEnumValueJsonExtension(),
  862. )
  863. )
  864. except EnumStringValueParseError:
  865. if not self.ignore_unknown_fields:
  866. raise
  867. def _GetJsonEnumValueOption(ev, extension_descriptor):
  868. """Helper to get the JsonEnumValueOptions for an enum value.
  869. Args:
  870. ev: The EnumValueDescriptor.
  871. extension_descriptor: The extension descriptor for 'pb.enumvalue.json'.
  872. Returns:
  873. The JsonEnumValueOptions message if the extension is present,
  874. otherwise None.
  875. """
  876. if ev.GetOptions().HasExtension(extension_descriptor):
  877. return ev.GetOptions().Extensions[extension_descriptor]
  878. return None
  879. def _GetCustomJsonEnumNames(
  880. enum_type, custom_enum_names_cache, enumvalue_json_extension=None
  881. ):
  882. """Helper to get a mapping from custom JSON name to EnumValueDescriptor.
  883. Args:
  884. enum_type: The EnumDescriptor.
  885. custom_enum_names_cache: A dict to store/lookup the cached map.
  886. enumvalue_json_extension: The extension descriptor for 'pb.enumvalue.json',
  887. or None to look it up in the default descriptor pool.
  888. Returns:
  889. A dict mapping custom JSON name strings to EnumValueDescriptors.
  890. """
  891. if enum_type in custom_enum_names_cache:
  892. return custom_enum_names_cache[enum_type]
  893. custom_names = {}
  894. if enumvalue_json_extension is None:
  895. # Options are always put on the default pool, so we only search the default pool.
  896. try:
  897. enumvalue_json_extension = descriptor_pool.Default().FindExtensionByName(
  898. 'pb.enumvalue.json'
  899. )
  900. except KeyError:
  901. enumvalue_json_extension = None
  902. if enumvalue_json_extension is not None:
  903. for ev in enum_type.values:
  904. options = ev.GetOptions()
  905. if options.HasExtension(enumvalue_json_extension):
  906. option = options.Extensions[enumvalue_json_extension]
  907. if option.HasField('string'):
  908. custom_names[option.string] = ev
  909. custom_enum_names_cache[enum_type] = custom_names
  910. return custom_names
  911. def _ConvertScalarFieldValue(
  912. value,
  913. field,
  914. path,
  915. custom_enum_names_cache,
  916. enumvalue_json_extension=None,
  917. require_str=False,
  918. ):
  919. """Convert a single scalar field value.
  920. Args:
  921. value: A scalar value to convert the scalar field value.
  922. field: The descriptor of the field to convert.
  923. path: parent path to log parse error info.
  924. custom_enum_names_cache: A dict to store/lookup custom enum names.
  925. enumvalue_json_extension: The extension descriptor for 'pb.enumvalue.json',
  926. or None if not loaded.
  927. require_str: If True, the field value must be a str.
  928. Returns:
  929. The converted scalar field value
  930. Raises:
  931. ParseError: In case of convert problems.
  932. EnumStringValueParseError: In case of unknown enum string value.
  933. """
  934. try:
  935. if field.cpp_type in _INT_TYPES:
  936. return _ConvertInteger(value)
  937. elif field.cpp_type in _FLOAT_TYPES:
  938. return _ConvertFloat(value, field)
  939. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  940. return _ConvertBool(value, require_str)
  941. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  942. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  943. if isinstance(value, str):
  944. encoded = value.encode('utf-8')
  945. else:
  946. encoded = value
  947. # Add extra padding '='
  948. padded_value = encoded + b'=' * (4 - len(encoded) % 4)
  949. return base64.urlsafe_b64decode(padded_value)
  950. else:
  951. # Checking for unpaired surrogates appears to be unreliable,
  952. # depending on the specific Python version, so we check manually.
  953. if _UNPAIRED_SURROGATE_PATTERN.search(value):
  954. raise ParseError('Unpaired surrogate')
  955. return value
  956. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  957. # Convert an enum value.
  958. enum_value = field.enum_type.values_by_name.get(value, None)
  959. # First check to see if we have a custom enum string.
  960. if (
  961. enum_value is None
  962. and isinstance(value, str)
  963. and enumvalue_json_extension is not None
  964. ):
  965. custom_names = _GetCustomJsonEnumNames(
  966. field.enum_type,
  967. custom_enum_names_cache,
  968. enumvalue_json_extension,
  969. )
  970. enum_value = custom_names.get(value, None)
  971. # If not, try parsing it as an integer.
  972. if enum_value is None:
  973. try:
  974. number = int(value)
  975. enum_value = field.enum_type.values_by_number.get(number, None)
  976. except ValueError as e:
  977. # Since parsing to integer failed and lookup in values_by_name didn't
  978. # find this name, we have an enum string value which is unknown.
  979. raise EnumStringValueParseError(
  980. 'Invalid enum value {0} for enum type {1}'.format(
  981. value, field.enum_type.full_name
  982. )
  983. ) from e
  984. if enum_value is None:
  985. if field.enum_type.is_closed:
  986. raise ParseError(
  987. 'Invalid enum value {0} for enum type {1}'.format(
  988. value, field.enum_type.full_name
  989. )
  990. )
  991. else:
  992. return number
  993. return enum_value.number
  994. except EnumStringValueParseError as e:
  995. raise EnumStringValueParseError('{0} at {1}'.format(e, path)) from e
  996. except ParseError as e:
  997. raise ParseError('{0} at {1}'.format(e, path)) from e
  998. def _ConvertInteger(value):
  999. """Convert an integer.
  1000. Args:
  1001. value: A scalar value to convert.
  1002. Returns:
  1003. The integer value.
  1004. Raises:
  1005. ParseError: If an integer couldn't be consumed.
  1006. """
  1007. if isinstance(value, float) and not value.is_integer():
  1008. raise ParseError("Couldn't parse integer: {0}".format(value))
  1009. if isinstance(value, str) and value.find(' ') != -1:
  1010. raise ParseError('Couldn\'t parse integer: "{0}"'.format(value))
  1011. if isinstance(value, bool):
  1012. raise ParseError(
  1013. 'Bool value {0} is not acceptable for integer field'.format(value)
  1014. )
  1015. try:
  1016. return int(value)
  1017. except ValueError as e:
  1018. # Attempt to parse as an integer-valued float.
  1019. try:
  1020. f = float(value)
  1021. except ValueError:
  1022. # Raise the original exception for the int parse.
  1023. raise e # pylint: disable=raise-missing-from
  1024. if not f.is_integer():
  1025. raise ParseError(
  1026. 'Couldn\'t parse non-integer string: "{0}"'.format(value)
  1027. ) from e
  1028. return int(f)
  1029. def _ConvertFloat(value, field):
  1030. """Convert an floating point number."""
  1031. if isinstance(value, float):
  1032. if math.isnan(value):
  1033. raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead')
  1034. if math.isinf(value):
  1035. if value > 0:
  1036. raise ParseError(
  1037. "Couldn't parse Infinity or value too large, "
  1038. 'use quoted "Infinity" instead'
  1039. )
  1040. else:
  1041. raise ParseError(
  1042. "Couldn't parse -Infinity or value too small, "
  1043. 'use quoted "-Infinity" instead'
  1044. )
  1045. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
  1046. # pylint: disable=protected-access
  1047. if value > type_checkers._FLOAT_MAX:
  1048. raise ParseError('Float value too large')
  1049. # pylint: disable=protected-access
  1050. if value < type_checkers._FLOAT_MIN:
  1051. raise ParseError('Float value too small')
  1052. if value == 'nan':
  1053. raise ParseError('Couldn\'t parse float "nan", use "NaN" instead')
  1054. try:
  1055. # Assume Python compatible syntax.
  1056. return float(value)
  1057. except ValueError as e:
  1058. # Check alternative spellings.
  1059. if value == _NEG_INFINITY:
  1060. return float('-inf')
  1061. elif value == _INFINITY:
  1062. return float('inf')
  1063. elif value == _NAN:
  1064. return float('nan')
  1065. else:
  1066. raise ParseError("Couldn't parse float: {0}".format(value)) from e
  1067. def _ConvertBool(value, require_str):
  1068. """Convert a boolean value.
  1069. Args:
  1070. value: A scalar value to convert.
  1071. require_str: If True, value must be a str.
  1072. Returns:
  1073. The bool parsed.
  1074. Raises:
  1075. ParseError: If a boolean value couldn't be consumed.
  1076. """
  1077. if require_str:
  1078. if value == 'true':
  1079. return True
  1080. elif value == 'false':
  1081. return False
  1082. else:
  1083. raise ParseError('Expected "true" or "false", not {0}'.format(value))
  1084. if not isinstance(value, bool):
  1085. raise ParseError('Expected true or false without quotes')
  1086. return value
  1087. _WKTJSONMETHODS = {
  1088. 'google.protobuf.Any': ['_AnyMessageToJsonObject', '_ConvertAnyMessage'],
  1089. 'google.protobuf.Duration': [
  1090. '_GenericMessageToJsonObject',
  1091. '_ConvertGenericMessage',
  1092. ],
  1093. 'google.protobuf.FieldMask': [
  1094. '_GenericMessageToJsonObject',
  1095. '_ConvertGenericMessage',
  1096. ],
  1097. 'google.protobuf.ListValue': [
  1098. '_ListValueMessageToJsonObject',
  1099. '_ConvertListOrTupleValueMessage',
  1100. ],
  1101. 'google.protobuf.Struct': [
  1102. '_StructMessageToJsonObject',
  1103. '_ConvertStructMessage',
  1104. ],
  1105. 'google.protobuf.Timestamp': [
  1106. '_GenericMessageToJsonObject',
  1107. '_ConvertGenericMessage',
  1108. ],
  1109. 'google.protobuf.Value': [
  1110. '_ValueMessageToJsonObject',
  1111. '_ConvertValueMessage',
  1112. ],
  1113. }