Python Algorithm to flattening JSON
Algorithm to flatten the deep JSON structure:
def flat(root, **args):
d = {}
for k, v in args.iteritems():
if type(v) == dict:
d.update(flat((k if root == None else '{}.{}'.format(root,k)),**v))
elif type(v) == list:
for idx, item in enumerate(v):
d.update(flat('{}.{}'.format(k if root == None else '{}.{}'.format(root,k),idx), **item))
else:
if root == None:
d['{}'.format(k)] = v
else:
d['{}.{}'.format(root,k)] = v
#print ('key: {}, val: {}'.format(k,v))
return d
for example, if you flatten the following JSON structure:
tt ={'name':{'firstName':'Tom', 'lastName':'Hanks'},
'orderlineitems':[{'rice':{'qty':2,'price':10}},{'bread':{'qty':1,'price':2}}],
'age':20, 'location':{'country':'AU','state_loc':{'state':'NSW', 'postal':2112}}}
flat(None,**tt)
The result is as follows:
{'age': 20,
'location.country': 'AU',
'location.state_loc.postal': 2112,
'location.state_loc.state': 'NSW',
'name.firstName': 'Tom',
'name.lastName': 'Hanks',
'orderlineitems.0.rice.price': 10,
'orderlineitems.0.rice.qty': 2,
'orderlineitems.1.bread.price': 2,
'orderlineitems.1.bread.qty': 1}
Comments
Post a Comment
commented your blog