Skip to content

Instantly share code, notes, and snippets.

@fadziljusri
Created November 26, 2019 04:16
Show Gist options
  • Save fadziljusri/a1e6a3883efc7741ce1a30f87bb445ab to your computer and use it in GitHub Desktop.
Save fadziljusri/a1e6a3883efc7741ce1a30f87bb445ab to your computer and use it in GitHub Desktop.
Flatten JSON object with nested keys into a single level.
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.
Eg:
{"a" : {"b": "c"}} => {"a.b": "c"}
"""
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