I am trying to normalize complex nested json in python but I am unable to parse all the objects out.
I am referencing the code from this page. https://medium.com/@amirziai/flattening-json-objects-in-python-f5343c794b10
sample_object = {'Name':'John', 'Location':{'City':'Los Angeles','State':'CA'}, 'hobbies':['Music', 'Running']}
def flatten_json(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
for a in x:
flatten(a, name)
else:
out[name[:-1]] = x
flatten(y)
return out
flat = flatten_json(sample_object)
print json_normalize(flat)
Return Result:
Name | Location_City | Location_State | Hobbies
-----+---------------+----------------+--------
John | Los Angeles | CA | Running
Expected Result:
Name | Location_City | Location_State | Hobbies
-----+---------------+----------------+--------
John | Los Angeles | CA | Running
John | Los Angeles | CA | Music