Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion jmespath/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ def _func_to_number(self, arg):
return int(arg)
except ValueError:
try:
return float(arg)
number = float(arg)
return number if math.isfinite(number) else None
except ValueError:
return None

Expand Down
12 changes: 12 additions & 0 deletions tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@

class TestFunctions(unittest.TestCase):

def test_to_number_rejects_nonfinite_strings(self):
for value in ('NaN', 'nan', 'Infinity', '-Infinity', 'inf', '-inf',
'1e999', '-1e999'):
with self.subTest(value=value):
result = jmespath.search('to_number(@)', value)
self.assertIsNone(result)
self.assertEqual(json.dumps(result, allow_nan=False), 'null')

def test_to_number_projection_filters_nonfinite_results(self):
values = ['1e2', 'NaN', '-Infinity', '1e999', '-0.5', 'not a number']
self.assertEqual(jmespath.search('[].to_number(@)', values), [100.0, -0.5])

def test_can_max_datetimes(self):
# This is python specific behavior, but JMESPath does not specify what
# you should do with language specific types. We're going to add the
Expand Down