Last active
November 15, 2019 09:48
-
-
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
This file contains 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
''' | |
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