Skip to content
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

Add negation of relative existence queries #168

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jg-rp
Copy link

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

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
Copy link
Collaborator

@jg-rp Thanks! One issue is that you 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
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