Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n3tsurge/a53290edf5861a4e4bf9da3b9a4f7310 to your computer and use it in GitHub Desktop.
Save n3tsurge/a53290edf5861a4e4bf9da3b9a4f7310 to your computer and use it in GitHub Desktop.
get_nested.py
def get_nested_field(message: dict, field: str):
'''
Iterates over nested fields to get the final desired value
e.g signal.rule.name should return the value of name
Paramters:
message (dict): A dictionary of values you want to iterate over
field (str): The field you want to extract from the message in dotted format
Return:
value: The extracted value, may be the response from this function calling itself again
'''
if isinstance(field, str):
args = field.split('.')
else:
args = field
if args and message:
element = args[0]
if element:
if isinstance(message, list):
values = []
value = [m for m in message if m is not None]
if any(isinstance(i, list) for i in value):
for l in value:
if isinstance(l, list):
values += [v for v in l if v is not None]
else:
values += [v for v in value if not isinstance(v, list)]
value = values
else:
value = message.get(element)
if isinstance(value, list):
if len(value) > 0 and isinstance(value[0], dict):
value = [get_nested_field(item, args[1:]) for item in value]
return value if len(args) == 1 else get_nested_field(value, args[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment