Created
August 16, 2018 04:59
-
-
Save Nitish18/e43305be7a668f1d0cff1857a561a9ed to your computer and use it in GitHub Desktop.
simple python function to flatten your json
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
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