Skip to content

Commit 883ec1c

Browse files
anandoleecopybara-github
authored andcommitted
Raise errors when serialize inf and nan for Value.number_value in json format. fixes #11259
PiperOrigin-RevId: 495976996
1 parent fc46e87 commit 883ec1c

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

python/google/protobuf/internal/json_format_test.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,23 @@ def testValueMessage(self):
608608
json_format.Parse('{"value": null}', message)
609609
self.assertEqual(message.value.WhichOneof('kind'), 'null_value')
610610

611+
def testValueMessageErrors(self):
612+
message = json_format_proto3_pb2.TestValue()
613+
message.value.number_value = math.inf
614+
with self.assertRaises(json_format.SerializeToJsonError) as cm:
615+
json_format.MessageToJson(message)
616+
self.assertEqual(
617+
'Failed to serialize value field: Fail to serialize Infinity for '
618+
'Value.number_value, which would parse as string_value.',
619+
str(cm.exception))
620+
message.value.number_value = math.nan
621+
with self.assertRaises(json_format.SerializeToJsonError) as cm:
622+
json_format.MessageToJson(message)
623+
self.assertEqual(
624+
'Failed to serialize value field: Fail to serialize NaN for '
625+
'Value.number_value, which would parse as string_value.',
626+
str(cm.exception))
627+
611628
def testListValueMessage(self):
612629
message = json_format_proto3_pb2.TestListValue()
613630
message.value.values.add().number_value = 11.1

python/google/protobuf/json_format.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,14 @@ def _ValueMessageToJsonObject(self, message):
354354
return None
355355
if which == 'list_value':
356356
return self._ListValueMessageToJsonObject(message.list_value)
357-
if which == 'struct_value':
358-
value = message.struct_value
357+
if which == 'number_value':
358+
value = message.number_value
359+
if math.isinf(value):
360+
raise ValueError('Fail to serialize Infinity for Value.number_value, '
361+
'which would parse as string_value')
362+
if math.isnan(value):
363+
raise ValueError('Fail to serialize NaN for Value.number_value, '
364+
'which would parse as string_value')
359365
else:
360366
value = getattr(message, which)
361367
oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]

0 commit comments

Comments
 (0)