project/analysis/util/iter.py

28 lines
941 B
Python

def json_path(obj: dict, key: str):# TODO: test me!
"""Query a nested dict with a dot-separated path"""
#if type(obj) is list and not "." in key:
# return obj[int(key)]
if type(obj) not in (dict, list):
raise ValueError("obj is no object (no list, too)")
if "." not in key:
if key not in obj:
return KeyError("key not in object", key)
return obj[key]
child_key = key.split(".")
if child_key[0] not in obj:
try:
index = int(child_key[0])
return json_path(obj[index], ".".join(child_key[1:]))
except:
raise KeyError("key not in object", key)
raise KeyError("key not in object", key)
return json_path(obj[child_key[0]], ".".join(child_key[1:]))
def combinate(settings: dict, entry: dict) -> bool: # TODO: better name...
"""combine all settings {<key>: <expected>} with entry using AND"""
result = True
for key, value in settings.items():
result = result and json_path(entry, key) == value
return result