Created
January 14, 2021 23:20
-
-
Save rooterkyberian/ceb4fc62094fa46c040ed2599658a3ce to your computer and use it in GitHub Desktop.
flatten_json.py
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 flatten_json(json_like): | |
""" | |
:param json_like: JSONable object | |
:return: flatten JSON-object, i.e. no inner dicts or lists | |
""" | |
from collections import deque | |
backlog = deque(("", json_like)) | |
output = {} | |
while backlog: | |
prefix, value = backlog.pop() | |
if isinstance(value, dict): | |
backlog.extend( | |
(f"{prefix}.{postfix}" if prefix else postfix, v) | |
for postfix, v in value.items() | |
) | |
if isinstance(value, list): | |
backlog.extend( | |
(f"{prefix}.{index}" if prefix else str(index), v) | |
for index, v in enumerate(value) | |
) | |
else: | |
output[prefix] = value | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment