Skip to content

Commit 8c9f0cf

Browse files
committed
Add membership of object data
1 parent 23c0f84 commit 8c9f0cf

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
**Features**
1010

11+
- 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).
1112
- 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.
1213
- 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.
1314

jsonpath/env.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Core JSONPath configuration object."""
2+
23
from __future__ import annotations
34

45
import re
@@ -548,9 +549,9 @@ def compare( # noqa: PLR0911
548549
return self._lt(right, left) or self._eq(left, right)
549550
if operator == "<=":
550551
return self._lt(left, right) or self._eq(left, right)
551-
if operator == "in" and isinstance(right, Sequence):
552+
if operator == "in" and isinstance(right, (Mapping, Sequence)):
552553
return left in right
553-
if operator == "contains" and isinstance(left, Sequence):
554+
if operator == "contains" and isinstance(left, (Mapping, Sequence)):
554555
return right in left
555556
if operator == "=~" and isinstance(right, re.Pattern) and isinstance(left, str):
556557
return bool(right.fullmatch(left))

tests/test_find.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,16 @@ class Case:
9797
}
9898
],
9999
),
100+
Case(
101+
description="object contains literal",
102+
path="$[[email protected] contains 'foo']",
103+
data=[{"a": {"foo": "bar"}}, {"a": {"bar": "baz"}}],
104+
want=[
105+
{
106+
"a": {"foo": "bar"},
107+
}
108+
],
109+
),
100110
Case(
101111
description="literal in array",
102112
path="$[?'foo' in @.a]",
@@ -107,6 +117,16 @@ class Case:
107117
}
108118
],
109119
),
120+
Case(
121+
description="literal in object",
122+
path="$[?'foo' in @.a]",
123+
data=[{"a": {"foo": "bar"}}, {"a": {"bar": "baz"}}],
124+
want=[
125+
{
126+
"a": {"foo": "bar"},
127+
}
128+
],
129+
),
110130
]
111131

112132

0 commit comments

Comments
 (0)