From 741ddbeed6cbd87a93ebdc22a89a21edd2537a5f Mon Sep 17 00:00:00 2001 From: Tony Moulton Date: Thu, 7 Jan 2016 15:51:55 -0500 Subject: [PATCH] Added support for floating point types in filter predicates --- jsonpath_rw_ext/parser.py | 10 +++++++++- jsonpath_rw_ext/tests/test_jsonpath_rw_ext.py | 13 ++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/jsonpath_rw_ext/parser.py b/jsonpath_rw_ext/parser.py index c61d2da..4f80c10 100644 --- a/jsonpath_rw_ext/parser.py +++ b/jsonpath_rw_ext/parser.py @@ -33,7 +33,7 @@ class ExtendedJsonPathLexer(lexer.JsonPathLexer): """Custom LALR-lexer for JsonPath""" literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-'] tokens = (parser.JsonPathLexer.tokens + - ['FILTER_OP', 'SORT_DIRECTION']) + ['FILTER_OP', 'SORT_DIRECTION', 'FLOAT']) t_FILTER_OP = r'==?|<=|>=|!=|<|>' @@ -49,6 +49,10 @@ class ExtendedJsonPathLexer(lexer.JsonPathLexer): t.type = self.reserved_words.get(t.value, 'ID') return t + def t_FLOAT(self, t): + r'-?\d+\.\d+' + t.value = float(t.value) + return t class ExtentedJsonPathParser(parser.JsonPathParser): """Custom LALR-parser for JsonPath""" @@ -61,9 +65,12 @@ class ExtentedJsonPathParser(parser.JsonPathParser): def p_jsonpath_operator_jsonpath(self, p): """jsonpath : NUMBER operator NUMBER + | FLOAT operator FLOAT | ID operator ID | NUMBER operator jsonpath + | FLOAT operator jsonpath | jsonpath operator NUMBER + | jsonpath operator FLOAT | jsonpath operator jsonpath """ @@ -101,6 +108,7 @@ class ExtentedJsonPathParser(parser.JsonPathParser): def p_expression(self, p): """expression : jsonpath | jsonpath FILTER_OP ID + | jsonpath FILTER_OP FLOAT | jsonpath FILTER_OP NUMBER """ if len(p) == 2: diff --git a/jsonpath_rw_ext/tests/test_jsonpath_rw_ext.py b/jsonpath_rw_ext/tests/test_jsonpath_rw_ext.py index e58f4d6..5431eac 100644 --- a/jsonpath_rw_ext/tests/test_jsonpath_rw_ext.py +++ b/jsonpath_rw_ext/tests/test_jsonpath_rw_ext.py @@ -93,7 +93,18 @@ class TestJsonpath_rw_ext(testscenarios.WithScenarios, {'cow': 8, 'cat': 3}]}, target=[{'cow': 8, 'cat': 2}, {'cow': 7, 'cat': 2}])), - + ('filter_float_gt', dict( + string='objects[?confidence>=0.5].prediction', + data={ + 'objects': [ + {'confidence': 0.42, + 'prediction': 'Good'}, + {'confidence': 0.58, + 'prediction': 'Bad'}, + ] + }, + target=['Bad'] + )), ('sort1', dict(string='objects[/cow]', data={'objects': [{'cat': 1, 'cow': 2}, {'cat': 2, 'cow': 1},