如何在json嵌套python中按值查找索引

2024-05-16 16:09:38 发布

您现在位置:Python中文网/ 问答频道 /正文

body = {
    'a': 1,
    'b': 'apple',
    'child': [
        {
            'a': 12,
            'b': 'banana',
            'child': [
                {
                    'a': 121,
                    'b': 'mango',
                    'child': [
                        {
                            'a': 1211,
                            'b': 'coconut',
                            'child': [dynamic nested]
                        }
                    ]
                },
                {
                    'a': 122,
                    'b': 'papaya',
                    'child': [
                        {
                            'a': 1221,
                            'b': 'lemon',
                            'child': [dynamic nested]
                        }
                    ]
                }
            ]
        },
        {
            'a': 13,
            'b': 'orenge',
            'child': [
                dynamic nested
            ]
        }
    ]
}

如果我想知道“couch”或“lemon”的索引(json body dynamic children子级,我不知道dee child,但khow'a'或'b'表示find index deep)

如何使用python获取索引

ex1: index of 'coconut' = [0,0,0]
ex2: index of 'lemon' = [0,1,0]

Tags: ofjsonchildappleindexbodydynamicnested
2条回答

出于教育目的,使用了相同的Akane算法,但采用了更具Python风格的方式:

def find_fruit(child, value, index=False):
    if child["b"] == value: 
        return []
    for i, ch in enumerate(child["child"]):
        if ch["b"] == value: 
            return [i]
        index = find_fruit(ch, value, index)
        if index: 
            return [i] + index

print(find(body, "coconut"))
def find(child, value, index=False):
     # First element in nested object is searched value
     if child["b"] == value:
         return []
     if len(child["child"]) == 0:
         return False
     for i in range(len(child["child"])):
         if child["child"][i]["b"] == value:
             index = [i]
             break
         else:
             index = find(child["child"][i], value, index)
             if index != False:
                  index = [i] + index
                 break
     return index
print(find(body, "coconut"))

使用递归函数

相关问题 更多 >