Skip to content

Instantly share code, notes, and snippets.

Last active Nov 15, 2019
What would you like to do?
Small Python script to flatten JSON which is useful in AWS lambdas occasionally
Originally found in
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
out[name[:-1]] = x
return out
flat = flatten_json(json_example)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment