Skip to content

Commit 62b53af

Browse files
author
dlacher
committed
added support for regex filters \n added support for . keyword
1 parent 4ee3fb6 commit 62b53af

File tree

5 files changed

+48
-4
lines changed

5 files changed

+48
-4
lines changed

jsonpath_ng/ext/filter.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,15 @@
1313

1414
import operator
1515
from six import moves
16+
import re
1617

1718
from .. import JSONPath, DatumInContext, Index
1819

20+
def contains(a,b):
21+
if re.search(b,a):
22+
return True
23+
return False
24+
1925

2026
OPERATOR_MAP = {
2127
'!=': operator.ne,
@@ -25,6 +31,7 @@
2531
'<': operator.lt,
2632
'>=': operator.ge,
2733
'>': operator.gt,
34+
'~=': contains
2835
}
2936

3037
def eval_exp(expressions,val):

jsonpath_ng/ext/iterable.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,29 @@ def __str__(self):
9090

9191
def __repr__(self):
9292
return 'Len()'
93+
94+
class Keys(JSONPath):
95+
"""The JSONPath referring to the keys of the current object.
96+
97+
Concrete syntax is '`keys`'.
98+
"""
99+
100+
def find(self, datum):
101+
datum = DatumInContext.wrap(datum)
102+
try:
103+
value = datum.value.keys()
104+
except Exception as e:
105+
return []
106+
else:
107+
return [DatumInContext(value[i],
108+
context=None,
109+
path=Keys()) for i in range (0, len(datum.value))]
110+
111+
def __eq__(self, other):
112+
return isinstance(other, Keys)
113+
114+
def __str__(self):
115+
return '`keys`'
116+
117+
def __repr__(self):
118+
return 'Keys()'

jsonpath_ng/ext/parser.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@
2222

2323
class ExtendedJsonPathLexer(lexer.JsonPathLexer):
2424
"""Custom LALR-lexer for JsonPath"""
25-
literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-']
25+
literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-', '!','~']
2626
tokens = (['BOOL'] +
2727
parser.JsonPathLexer.tokens +
2828
['FILTER_OP', 'SORT_DIRECTION', 'FLOAT'])
29-
30-
t_FILTER_OP = r'==?|<=|>=|!=|<|>'
29+
print "tokens {}".format(tokens)
30+
t_FILTER_OP = r'==?|<=|>=|!=|<|>|~='
3131

3232
def t_BOOL(self, t):
3333
r'true|false'
@@ -93,6 +93,8 @@ def p_jsonpath_named_operator(self, p):
9393
"jsonpath : NAMED_OPERATOR"
9494
if p[1] == 'len':
9595
p[0] = _iterable.Len()
96+
elif p[1] == 'keys':
97+
p[0] = _iterable.Keys()
9698
elif p[1] == 'sorted':
9799
p[0] = _iterable.SortedThis()
98100
elif p[1].startswith("split("):

jsonpath_ng/lexer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def tokenize(self, string):
4848
#
4949
# Anyhow, it is pythonic to give some rope to hang oneself with :-)
5050

51-
literals = ['*', '.', '[', ']', '(', ')', '$', ',', ':', '|', '&', '!']
51+
literals = ['*', '.', '[', ']', '(', ')', '$', ',', ':', '|', '&']
5252

5353
reserved_words = { 'where': 'WHERE' }
5454

tests/test_jsonpath_rw_ext.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,21 @@ class Testjsonpath_ng_ext(testscenarios.WithScenarios,
9696
('len_list', dict(string='objects.`len`',
9797
data={'objects': ['alpha', 'gamma', 'beta']},
9898
target=3)),
99+
('keys_list', dict(string='objects.`keys`',
100+
data={'objects': ['alpha', 'gamma', 'beta']},
101+
target=[])),
99102
('len_dict', dict(string='objects.`len`',
100103
data={'objects': {'cow': 'moo', 'cat': 'neigh'}},
101104
target=2)),
105+
('keys_dict', dict(string='objects.`keys`',
106+
data={'objects': {'cow': 'moo', 'cat': 'neigh'}},
107+
target=['cow','cat'])),
102108
('len_str', dict(string='objects[0].`len`',
103109
data={'objects': ['alpha', 'gamma']},
104110
target=5)),
111+
('contains_filter', dict(string='objects[?id ~= "v.*[1-9]"].id',
112+
data={'objects': [{'id':'vasll1'},{'id':'v2'},{'id':'vaal3'},{'id':'other'},{'id':'val'}]},
113+
target=['vasll1','v2','vaal3'])),
105114

106115
('filter_exists_syntax1', dict(string='objects[?cow]',
107116
data={'objects': [{'cow': 'moo'},

0 commit comments

Comments
 (0)