Skip to content

Commit 2d9e952

Browse files
committed
Add pointers to the fluent API
1 parent 6fc896a commit 2d9e952

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

docs/query.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,23 @@ for value in values:
2424
# ...
2525
```
2626

27+
`Query` objects are iterable and can only be iterated once. Pass the query to `list()` (or other sequence) to get a list of results that can be iterated multiple times or otherwise manipulated.
28+
29+
```python
30+
from jsonpath import query
31+
32+
# data = ...
33+
34+
values = list(
35+
query("$.some[[email protected]]", data)
36+
.skip(5)
37+
.limit(10)
38+
.values()
39+
)
40+
41+
print(values[1])
42+
```
43+
2744
## Chainable methods
2845

2946
The following `Query` methods all return `self` (the same `Query` instance), so method calls can be chained to further manipulate the underlying iterator.

jsonpath/fluent_api.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
if TYPE_CHECKING:
1313
from jsonpath import JSONPathMatch
14+
from jsonpath import JSONPointer
1415

1516

1617
class Query:
@@ -123,14 +124,16 @@ def values(self) -> Iterable[object]:
123124
return (m.obj for m in self._it)
124125

125126
def locations(self) -> Iterable[str]:
126-
"""Return an iterable of normalized paths for each match."""
127+
"""Return an iterable of normalized paths, one for each match."""
127128
return (m.path for m in self._it)
128129

129130
def items(self) -> Iterable[Tuple[str, object]]:
130-
"""Return an iterable of (object, normalized path) tuples for each match."""
131+
"""Return an iterable of (object, path) tuples, one for each match."""
131132
return ((m.path, m.obj) for m in self._it)
132133

133-
# TODO: def pointers
134+
def pointers(self) -> Iterable[JSONPointer]:
135+
"""Return an iterable of JSONPointers, one for each match."""
136+
return (m.pointer() for m in self._it)
134137

135138
def first_one(self) -> Optional[JSONPathMatch]:
136139
"""Return the first `JSONPathMatch` or `None` if there were no matches."""

tests/test_fluent_api.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import pytest
33

44
from jsonpath import JSONPathMatch
5+
from jsonpath import JSONPointer
56
from jsonpath import query
67

78

@@ -240,3 +241,10 @@ def test_query_tee() -> None:
240241
rv2 = it2.skip(2).one()
241242
assert rv2 is not None
242243
assert rv2.value == 2 # noqa: PLR2004
244+
245+
246+
def test_query_pointers() -> None:
247+
"""Test that we can get pointers from a query."""
248+
pointers = list(query("$.some.*", {"some": [0, 1, 2, 3]}).pointers())
249+
assert len(pointers) == 4 # noqa: PLR2004
250+
assert pointers[0] == JSONPointer("/some/0")

0 commit comments

Comments
 (0)