Skip to content

Instantly share code, notes, and snippets.

@chavarera
Created December 3, 2021 05:11
Show Gist options
  • Save chavarera/be3fded6adc5c4fd72380012ec9799ad to your computer and use it in GitHub Desktop.
Save chavarera/be3fded6adc5c4fd72380012ec9799ad to your computer and use it in GitHub Desktop.
flatten json
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