Created
December 3, 2021 05:11
-
-
Save chavarera/be3fded6adc5c4fd72380012ec9799ad to your computer and use it in GitHub Desktop.
flatten json
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
import pandas as pd | |
from json import dump, load | |
def flat(object, sep='.'): | |
"""flatten nested object | |
Args: | |
object ([dict]): input document | |
sep (str, optional): an seperator. Defaults to '.'. | |
Returns: | |
[dict]: flatten object | |
""" | |
out = {} | |
def flatten(x, name=''): | |
if type(x) is dict: | |
for a in x: | |
flatten(x[a], name + a + sep) | |
elif type(x) is list: | |
i = 0 | |
for a in x: | |
flatten(a, name + str(i) + sep) | |
i += 1 | |
else: | |
out[name[:-1]] = x | |
flatten(object) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment