Skip to content

Add negation of relative existence queries#168

Open
jg-rp wants to merge 1 commit into
h2non:masterfrom
jg-rp:logical-negation
Open

Add negation of relative existence queries#168
jg-rp wants to merge 1 commit into
h2non:masterfrom
jg-rp:logical-negation

Conversation

@jg-rp

@jg-rp jg-rp commented Apr 20, 2024

Copy link
Copy Markdown

This pull request implements the not operator (!) for negating a relative query when testing for existence. This is a potential solution for #167.

Sticking with example data from #167, this example selects values from data that don't contain a type property.

from jsonpath_ng.ext import parse

data = [
    {"name": "foo", "data": [{"value": "bar"}]},
    {"name": "foo", "data": [{"value": "bar", "type": "foo"}]},
]
 
query = parse("$[?!@..['type']]")  # or "$[?!data[*].type]"
matches = query.find(data)

print([m.value for m in matches])
# [{'name': 'foo', 'data': [{'value': 'bar'}]}]

To keep this PR small, I've deliberately avoided implementing logical negation for other filter expression types and any refactoring of ext.filter.Expression.

@jg-rp jg-rp changed the title Add logical negation of relative query existence Add negation of relative existence queries Apr 29, 2024
@michaelmior

michaelmior commented Jun 11, 2024

Copy link
Copy Markdown
Collaborator

@jg-rp Thanks! One issue is that your change to the find function can cause returning a boolean instead of a list of results. I think something like the below should work.

         if self.op == "!":
             # Negated relative query existence test
-            return not datum
+            if not datum:
+                return [datum]
+            else:
+                return []

@michaelmior

Copy link
Copy Markdown
Collaborator

It would also be nice if you could add your example above to the README.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants