Skip to content

Instantly share code, notes, and snippets.

@bsmth
Last active November 15, 2019 09:48
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 bsmth/788d284f2baa3f5edbcfd91c1ca712b1 to your computer and use it in GitHub Desktop.
Save bsmth/788d284f2baa3f5edbcfd91c1ca712b1 to your computer and use it in GitHub Desktop.
Small Python script to flatten JSON which is useful in AWS lambdas occasionally
'''
Originally found in https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10
edited to shorten key names as far as possible.
'''
import json
json_example = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
def flatten_json(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], 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(y)
return out
flat = flatten_json(json_example)
print(json.dumps(flat))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment