Created
November 15, 2018 01:53
-
-
Save alinazhanguwo/03206c554c1a8fcbe42a7d971efc7b26 to your computer and use it in GitHub Desktop.
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
from itertools import chain, starmap | |
def flatten_json_iterative_solution(dictionary): | |
"""Flatten a nested json file""" | |
def unpack(parent_key, parent_value): | |
"""Unpack one level of nesting in json file""" | |
# Unpack one level only!!! | |
if isinstance(parent_value, dict): | |
for key, value in parent_value.items(): | |
temp1 = parent_key + '_' + key | |
yield temp1, value | |
elif isinstance(parent_value, list): | |
i = 0 | |
for value in parent_value: | |
temp2 = parent_key + '_'+str(i) | |
i += 1 | |
yield temp2, value | |
else: | |
yield parent_key, parent_value | |
# Keep iterating until the termination condition is satisfied | |
while True: | |
# Keep unpacking the json file until all values are atomic elements (not dictionary or list) | |
dictionary = dict(chain.from_iterable(starmap(unpack, dictionary.items()))) | |
# Terminate condition: not any value in the json file is dictionary or list | |
if not any(isinstance(value, dict) for value in dictionary.values()) and \ | |
not any(isinstance(value, list) for value in dictionary.values()): | |
break | |
return dictionary |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want all list values below each other in 1 column and not in separate column. How can i write code for that.