Skip to content

Instantly share code, notes, and snippets.

@alinazhanguwo
Created November 15, 2018 01:53
Show Gist options
  • Save alinazhanguwo/03206c554c1a8fcbe42a7d971efc7b26 to your computer and use it in GitHub Desktop.
Save alinazhanguwo/03206c554c1a8fcbe42a7d971efc7b26 to your computer and use it in GitHub Desktop.
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
@ImNick23
Copy link

I want all list values below each other in 1 column and not in separate column. How can i write code for that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment