Created
November 9, 2017 15:08
-
-
Save filinvadim/60893bd62d91aaec74ccb71d80bbc65d to your computer and use it in GitHub Desktop.
Recursive JSON parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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