我有一个如下格式的json。
json_tree = {
"Gardens": {
"Seaside": {
"@loc": "porch",
"@myID": "1.2.3",
"Tid": "1",
"InfoList": {
"status": {
"@default": "0",
"@myID": "26"
},
"count": {
"@default": "0",
"@myID": "1"
}
},
"BackYard": {
"@myID": "75",
"Tid": "2",
"InfoList": {
"status": {
"@default": "6",
"@myID": "32"
},
"count": {
"@default": "0",
"@myID": "2"
}
}
}
}
}
}当我搜索关键字‘Seaside’或"Backyard“时,我希望能够返回"@loc”值。我希望它是通用的,因为关键字可以是任何字符串。
目前,我有以下方法,当我搜索"Seaside“时,它只返回"@loc”,当我搜索"BackYard“时,它不返回任何内容。注意:"BackYard“与"Seaside”具有相同的"@loc“,因为它嵌套在其中。
我不确定这段代码中缺少了什么。
我的实现:
def getLoc(json_tree , key):
for k1,v1 in json_tree.items():
for k,v in v1.items():
if '@loc' in v and v['@loc'] is not None and str(k) == key:
return v['@loc']The output should be "backyard" for the following example.
getLoc(json_tree, "Seaside")
getLoc(json_tree, "Backyard")发布于 2019-08-06 02:41:14
您可以对生成器使用递归:
def get_vals(d, _key, _score = None):
for a, b in d.items():
if _key == a:
yield b.get('@loc', _score)
if isinstance(b, dict):
yield from get_vals(b, _key, b.get('@loc', _score))
elif isinstance(b, list):
for i in b:
yield from get_vals(i, _key, b.get('@loc', _score))
print(list(get_vals(json_tree, 'Seaside')))
print(list(get_vals(json_tree, 'BackYard')))输出:
['porch']
['porch']https://stackoverflow.com/questions/57364340
复制相似问题