Skip to content

Commit 61dba69

Browse files
authored
Merge pull request #11 from mahmoudajawad/main
feat: Custom eval implementation
2 parents 8dcf854 + eb62abe commit 61dba69

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

jsonpath/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ class JSONPath:
7777
subx = defaultdict(list)
7878
result: list
7979
result_type: str
80+
eval_func: callable
8081

8182
def __init__(self, expr: str):
8283
expr = self._parse_expr(expr)
@@ -86,7 +87,7 @@ def __init__(self, expr: str):
8687

8788
self.caller_globals = sys._getframe(1).f_globals
8889

89-
def parse(self, obj, result_type="VALUE"):
90+
def parse(self, obj, result_type="VALUE", eval_func=eval):
9091
if not isinstance(obj, (list, dict)):
9192
raise TypeError("obj must be a list or a dict.")
9293

@@ -95,6 +96,7 @@ def parse(self, obj, result_type="VALUE"):
9596
f"result_type must be one of {tuple(JSONPath.RESULT_TYPE.keys())}"
9697
)
9798
self.result_type = result_type
99+
self.eval_func = eval_func
98100

99101
self.result = []
100102
self._trace(obj, 0, "$")
@@ -212,7 +214,7 @@ def _sorter(obj, sortbys):
212214
def _filter(self, obj, i: int, path: str, step: str):
213215
r = False
214216
try:
215-
r = eval(step, None, {"__obj": obj})
217+
r = self.eval_func(step, None, {"__obj": obj})
216218
except Exception as err:
217219
logger.error(err)
218220
if r:
@@ -263,7 +265,7 @@ def _trace(self, obj, i: int, path):
263265
# slice
264266
if isinstance(obj, list) and JSONPath.REP_SLICE_CONTENT.fullmatch(step):
265267
obj = list(enumerate(obj))
266-
vals = eval(f"obj[{step}]")
268+
vals = self.eval_func(f"obj[{step}]")
267269
for idx, v in vals:
268270
self._trace(v, i + 1, f"{path}{JSONPath.SEP}{idx}")
269271
return

0 commit comments

Comments
 (0)