Skip to content

Instantly share code, notes, and snippets.

@sreevardhanreddi
Created August 8, 2018 12:12
Show Gist options
  • Save sreevardhanreddi/a8959d9d3fa025485c10a8b4c078560d to your computer and use it in GitHub Desktop.
Save sreevardhanreddi/a8959d9d3fa025485c10a8b4c078560d to your computer and use it in GitHub Desktop.
converts a nested dictionary to a flattened version of dictionary, uses recursion
def json_flat_dict(da):
v = {}
for i in da:
if type(da[i]) == dict:
g = json_flat_dict(da[i])
for j in g:
v[i + '__' + j] = g[j]
else:
v[i] = da[i]
return v
json_flat_dict({
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment