Skip to content

Instantly share code, notes, and snippets.

@sardbaba
Created June 8, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sardbaba/be5da3fad0def575a83b8bb026f51de8 to your computer and use it in GitHub Desktop.
Save sardbaba/be5da3fad0def575a83b8bb026f51de8 to your computer and use it in GitHub Desktop.
def flatten_json(nested_json, name='', exclude=['']):
"""Flatten json object with nested keys into a single level.
Args:
nested_json: A nested json object.
name: A name to cancatenate to the sublevels keys
exclude: Keys to exclude from output.
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name='', exclude=exclude):
if type(x) is dict:
for a in x:
if a not in exclude:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + '_')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json, name)
return out
## Usage, where "df" is a pandas dataframe
df2 = pd.DataFrame([flatten_json(x, 'json_column_name') for x in df['json_column_name']])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment