Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions jsonpath/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import weakref

from abc import abstractmethod
from contextlib import suppress
from contextvars import ContextVar
from typing import (
Any,
Expand Down Expand Up @@ -455,16 +456,16 @@ def _get_partial_expression(self) -> str:
return f"[{self.idx!s}]"

def find(self, element: Any) -> List[Any]:
if self.idx is None and isinstance(element, list):
return element
elif (
isinstance(self.idx, int)
and isinstance(element, list)
and self.idx < len(element)
):
return [element[self.idx]]
elif isinstance(self.idx, Slice):
return self.idx.find(element)
if isinstance(element, list):
if self.idx is None:
return element
elif isinstance(self.idx, int):
with suppress(IndexError):
return [element[self.idx]]
elif isinstance(self.idx, Slice):
return self.idx.find(element)
else:
raise AssertionError(f"self.idx={self.idx!r} is not valid")

raise JSONPathFindError

Expand Down
4 changes: 4 additions & 0 deletions tests/test_lark.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ def test_parse_check_and_extract(expression, data, expect):
("boo.*.boo", {"boo": {"boo": {"boo": 1}, "bar": {"bar": 2}}}, [1]),
("boo.*.boo", {"boo": {"boo": {"boo": 1}, "bar": 1}}, [1]),
("$[0]", [1, 2], [1]),
("$[1]", [1, 2], [2]),
("$[2]", [1, 2], []),
("$[-1]", [], []),
("$[-1]", [1], [1]),
("boo[0]", {"boo": [1, 2]}, [1]),
("$[*]", [1, 2], [1, 2]),
("$[:1]", [1, 2], [1]),
Expand Down