Skip to content

Instantly share code, notes, and snippets.

@Nitish18
Created August 16, 2018 04:59
Show Gist options
  • Save Nitish18/e43305be7a668f1d0cff1857a561a9ed to your computer and use it in GitHub Desktop.
Save Nitish18/e43305be7a668f1d0cff1857a561a9ed to your computer and use it in GitHub Desktop.
simple python function to flatten your json
import json
def main():
demo_obj = {
'a' : 1,
'b' : {
'c' : 'd',
'e' : {
'x' : 'y'
}
},
'g' : 'h'
}
final = {}
for key,val in demo_obj.items():
if isinstance(val,dict):
child_dict = flatten(val, key)
final.update(child_dict)
else:
final[key] = val
print "your flattened json","\n"
print final
def flatten(dict1, key1):
data = {}
for key,val in dict1.items():
if isinstance(val, dict):
obj = flatten(val, str(key1) + '.' + str(key))
data.update(obj)
else:
data.update({str(key1)+'.'+str(key) : val})
return data
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment