Created
June 8, 2020 15:22
-
-
Save sardbaba/be5da3fad0def575a83b8bb026f51de8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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