Skip to content

Commit 89550c9

Browse files
author
Filip Uhlik
committed
[#186] options: add default not found value option
1 parent 2ad18b0 commit 89550c9

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

jmespath/visitor.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import operator
2+
from numbers import Number
23

34
from jmespath import functions
45
from jmespath.compat import string_type
5-
from numbers import Number
66

77

88
def _equals(x, y):
@@ -58,7 +58,7 @@ def _is_actual_number(x):
5858

5959
class Options(object):
6060
"""Options to control how a JMESPath function is evaluated."""
61-
def __init__(self, dict_cls=None, custom_functions=None):
61+
def __init__(self, dict_cls=None, custom_functions=None, not_found_value=None):
6262
#: The class to use when creating a dict. The interpreter
6363
# may create dictionaries during the evaluation of a JMESPath
6464
# expression. For example, a multi-select hash will
@@ -69,6 +69,7 @@ def __init__(self, dict_cls=None, custom_functions=None):
6969
# have predictable key ordering.
7070
self.dict_cls = dict_cls
7171
self.custom_functions = custom_functions
72+
self.not_found_value = not_found_value
7273

7374

7475
class _Expression(object):
@@ -133,9 +134,9 @@ def visit_subexpression(self, node, value):
133134

134135
def visit_field(self, node, value):
135136
try:
136-
return value.get(node['value'])
137+
return value.get(node['value'], self._options.not_found_value)
137138
except AttributeError:
138-
return None
139+
return self._options.not_found_value
139140

140141
def visit_comparator(self, node, value):
141142
# Common case: comparator is == or !=
@@ -298,7 +299,7 @@ def _is_false(self, value):
298299
# because the truth/false values are different between
299300
# python and jmespath.
300301
return (value == '' or value == [] or value == {} or value is None or
301-
value is False)
302+
value is False or value == self._options.not_found_value)
302303

303304
def _is_true(self, value):
304305
return not self._is_false(value)

tests/test_search.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,15 @@ def test_can_handle_decimals_as_numeric_type(self):
6262
result = decimal.Decimal('3')
6363
self.assertEqual(jmespath.search('[?a >= `1`].a', [{'a': result}]),
6464
[result])
65+
66+
67+
class TestNotFoundValueOption(unittest.TestCase):
68+
opt = jmespath.Options(not_found_value='foo')
69+
70+
def test_can_supply_custom_not_found_value(self):
71+
value = jmespath.search('b', {'a': 1}, self.opt)
72+
self.assertEqual(value, 'foo')
73+
74+
def test_custom_value_is_treated_as_false(self):
75+
value = jmespath.search('b || a', {'a': 1}, self.opt)
76+
self.assertEqual(value, 1)

0 commit comments

Comments
 (0)