Skip to content

Add negation of relative existence queries #168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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: 3 additions & 0 deletions jsonpath_ng/ext/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ def __init__(self, target, op, value):
def find(self, datum):
datum = self.target.find(DatumInContext.wrap(datum))

if self.op == "!":
# Negated relative query existence test
return not datum
if not datum:
return []
if self.op is None:
Expand Down
6 changes: 5 additions & 1 deletion jsonpath_ng/ext/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

class ExtendedJsonPathLexer(lexer.JsonPathLexer):
"""Custom LALR-lexer for JsonPath"""
literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-']
literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-', '!']
tokens = (['BOOL'] +
parser.JsonPathLexer.tokens +
['FILTER_OP', 'SORT_DIRECTION', 'FLOAT'])
Expand Down Expand Up @@ -120,6 +120,10 @@ def p_expression(self, p):
__, left, op, right = p
p[0] = _filter.Expression(left, op, right)

def p_expression_not(self, p):
"expression : '!' jsonpath"
p[0] = _filter.Expression(p[2], p[1], None)

def p_expressions_expression(self, p):
"expressions : expression"
p[0] = [p[1]]
Expand Down
46 changes: 46 additions & 0 deletions tests/test_jsonpath_rw_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@
[{"cow": "moo"}],
id="filter_eq3",
),
pytest.param(
'objects[?cow!="moo"]',
{"objects": [{"cow": "moo"}, {"cow": "neigh"}]},
[{"cow": "neigh"}],
id="filter_ne",
),
pytest.param(
"objects[?cow>5]",
{"objects": [{"cow": 8}, {"cow": 7}, {"cow": 5}, {"cow": "neigh"}]},
Expand Down Expand Up @@ -448,6 +454,46 @@
["green"],
id="boolean-filter-string-true-string-literal",
),
pytest.param(
'$[?!@..["type"]]',
[
{
"name": "foo",
"data": [{"value": "bar"}]
},
{
"name": "foo",
"data": [{"value": "bar", "type": "foo"}]
}
],
[
{
"name": "foo",
"data": [{"value": "bar"}]
}
],
id="negated_relative_query_existence"
),
pytest.param(
'$[?!data[*].type]',
[
{
"name": "foo",
"data": [{"value": "bar"}]
},
{
"name": "foo",
"data": [{"value": "bar", "type": "foo"}]
}
],
[
{
"name": "foo",
"data": [{"value": "bar"}]
}
],
id="negated_relative_query_existence_implicit_this"
),
)


Expand Down