Skip to content

Commit 2e137e8

Browse files
committed
extended functionality of osw.data.import_utility.jsonpath_search_and_return_list() to allow val_key=None to return the value of the result directly
1 parent 17bc26c commit 2e137e8

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

src/osw/data/import_utility.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -312,28 +312,38 @@ def flatten_list(nested_list):
312312

313313

314314
def jsonpath_search_and_return_list_simple(
315-
jp_str: str, val_key: str, search_tar: dict
315+
jp_str: str, val_key: Union[str, None], search_tar: dict
316316
) -> Union[list, None]:
317317
jp_parse = jp.parse(path=jp_str)
318318
result = jp_parse.find(search_tar)
319319
list_ = []
320320
if result:
321321
for res in result:
322-
list_.append(res.value[val_key])
322+
if val_key is None:
323+
list_.append(res.value)
324+
else:
325+
list_.append(res.value[val_key])
323326
return list_
324327

325328

326329
def jsonpath_search_and_return_list(
327-
jp_str: str, val_key: str, search_tar: dict, class_to_match=None, warn: bool = True
330+
jp_str: str,
331+
val_key: Union[str, None],
332+
search_tar: dict,
333+
class_to_match=None,
334+
warn: bool = True,
328335
) -> Union[list, None]:
329-
"""
336+
"""Searches through a dictionary for a set json path string and returns the
337+
values of matching results or a certain value matching val_key as a list.
338+
class_to_match can be specified to filter results by class.
330339
331340
Parameters
332341
----------
333342
jp_str:
334343
The jsonpath string to search for
335344
val_key:
336-
The key of the value (of the search results) to be returned in a list
345+
The key of the value (of the search results) to be returned in a list. If set to
346+
None, the value of the search result is returned.
337347
search_tar:
338348
The dictionary to search in with jsonpath
339349
class_to_match:
@@ -386,10 +396,17 @@ def jsonpath_search_and_return_list(
386396
for res in result:
387397
res_type = res.value["type"]
388398
res_type.sort()
399+
append = False
389400
if class_to_match is None:
390-
list_.append(res.value[val_key])
401+
append = True
391402
elif isclass(res.value, class_to_match):
392-
list_.append(res.value[val_key])
403+
append = True
404+
if append:
405+
if val_key is None:
406+
list_.append(res.value)
407+
else:
408+
list_.append(res.value[val_key])
409+
393410
if len(list_) == 0 and warn:
394411
warnings.warn(
395412
f"jsonpath_search_and_return_list() did not find any "

0 commit comments

Comments
 (0)