我有一个json,它只是一个无序转储,它包含字典,列表和unicode值的混合嵌套,深度范围为1到10。这是我正在处理的粗略简化示例:
{'name': 'TheDude',
'age': '19',
'hobbies': {
'love': 'eating',
'hate': 'reading',
'like': [
{'outdoor': {
'teamsport': 'soccer',
}
}
]
}
}
我想要以下输出(基于上述内容):
[name, age, hobbies_love, hobbies_hate, hobbies_like_outdoor_teamsport]
我尝试了以下代码:
def printinoice(dictionary,arr):
for k, v in dictionary.iteritems():
arr.append(k)
if isinstance(v, dict):
for result in printinoice(v,arr):
arr.append(result)
elif isinstance(v, list):
for d in v:
for result in printinoice(d,arr):
arr.append(result)
return arr
基于this,但到目前为止还没有运气。任何人都对如何使其工作有好主意吗?
答案 0 :(得分:2)
以下递归函数将起作用:
setCurrentPoint(new Point(10,8));
最简单的做法是不为函数参数假定给定类型,这样您就可以沿递归传递任何嵌套的东西(即def deep_keys(dct):
if not isinstance(dct, (dict, list)):
return ['']
if isinstance(dct, list):
return [dk for x in dct for dk in deep_keys(x)]
return [k+('_'+dk if dk else '') for k, v in dct.items() for dk in deep_keys(v)]
>>> deep_keys(d)
['name', 'age', 'hobbies_love', 'hobbies_hate', 'hobbies_like_outdoor_teamsport']
元素和list
值)。