Skip to content

Commit

Permalink
Add membership of object data
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp committed Jul 6, 2024
1 parent 23c0f84 commit 8c9f0cf
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

**Features**

- Allow JSONPath filter expression membership operators (`contains` and `in`) to operate on object/mapping data as well as arrays/sequences. See [#55](https://github.com/jg-rp/python-jsonpath/issues/55).
- Added a `select` method to the JSONPath [query iterator interface](https://jg-rp.github.io/python-jsonpath/query/), generating a projection of each JSONPath match by selecting a subset of its values.
- Added the `addne` and `addap` operations to [JSONPatch](https://jg-rp.github.io/python-jsonpath/api/#jsonpath.JSONPatch). `addne` (add if not exists) is like the standard `add` operation, but only adds object keys/values if the key does not exist. `addap` (add or append) is like the standard `add` operation, but assumes an index of `-` if the target index can not be resolved.

Expand Down
5 changes: 3 additions & 2 deletions jsonpath/env.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Core JSONPath configuration object."""

from __future__ import annotations

import re
Expand Down Expand Up @@ -548,9 +549,9 @@ def compare( # noqa: PLR0911
return self._lt(right, left) or self._eq(left, right)
if operator == "<=":
return self._lt(left, right) or self._eq(left, right)
if operator == "in" and isinstance(right, Sequence):
if operator == "in" and isinstance(right, (Mapping, Sequence)):
return left in right
if operator == "contains" and isinstance(left, Sequence):
if operator == "contains" and isinstance(left, (Mapping, Sequence)):
return right in left
if operator == "=~" and isinstance(right, re.Pattern) and isinstance(left, str):
return bool(right.fullmatch(left))
Expand Down
20 changes: 20 additions & 0 deletions tests/test_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ class Case:
}
],
),
Case(
description="object contains literal",
path="$[[email protected] contains 'foo']",
data=[{"a": {"foo": "bar"}}, {"a": {"bar": "baz"}}],
want=[
{
"a": {"foo": "bar"},
}
],
),
Case(
description="literal in array",
path="$[?'foo' in @.a]",
Expand All @@ -107,6 +117,16 @@ class Case:
}
],
),
Case(
description="literal in object",
path="$[?'foo' in @.a]",
data=[{"a": {"foo": "bar"}}, {"a": {"bar": "baz"}}],
want=[
{
"a": {"foo": "bar"},
}
],
),
]


Expand Down

0 comments on commit 8c9f0cf

Please sign in to comment.