Skip to content

Instantly share code, notes, and snippets.

@alinazhanguwo
Last active September 22, 2023 15:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alinazhanguwo/a54f28f1fd9335dc69f7c32dd7a75b12 to your computer and use it in GitHub Desktop.
Save alinazhanguwo/a54f28f1fd9335dc69f7c32dd7a75b12 to your computer and use it in GitHub Desktop.
def flatten_json(nested_json):
"""
Flatten json object with nested keys into a single level.
Args:
nested_json: A nested json object.
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment