Skip to content

Instantly share code, notes, and snippets.

@filinvadim
Created November 9, 2017 15:08
Show Gist options
  • Save filinvadim/60893bd62d91aaec74ccb71d80bbc65d to your computer and use it in GitHub Desktop.
Save filinvadim/60893bd62d91aaec74ccb71d80bbc65d to your computer and use it in GitHub Desktop.
Recursive JSON parsing
def contains(self, element, list_wrap=False):
"""
Recursively seeks for requested keyword or list of keywords
:param data: json-type dict
:param element: str or list
:return: list or None
"""
collected_elements = []
def _recursively_seek(data):
if isinstance(data, dict):
for key, value in data.items():
if key in element:
if isinstance(value, list):
for item in value:
collected_elements.append(item)
elif value is None:
collected_elements.append(key)
else:
collected_elements.append(value)
_recursively_seek(value)
elif isinstance(data, list):
for item in data:
_recursively_seek(item)
elif isinstance(data, tuple):
_recursively_seek(dict(data))
_recursively_seek(self._data)
if len(collected_elements) == 0:
return None
elif len(collected_elements) == 1:
if list_wrap:
return collected_elements
return collected_elements[0]
return collected_elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment