【发布时间】:2017-04-07 14:18:22
【问题描述】:
我正在尝试在 python 中规范化复杂的嵌套 json,但我无法解析出所有对象。
我正在引用此页面中的代码。 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)
返回结果:
Name | Location_City | Location_State | Hobbies
-----+---------------+----------------+--------
John | Los Angeles | CA | Running
预期结果:
Name | Location_City | Location_State | Hobbies
-----+---------------+----------------+--------
John | Los Angeles | CA | Running
John | Los Angeles | CA | Music
【问题讨论】:
标签: python json loops nested-loops