【问题标题】:Return all values for a path of keys in a json when target key in list and non list当目标键在列表和非列表中时,返回 json 中键路径的所有值
【发布时间】:2020-05-21 17:21:39
【问题描述】:

假设我有这个 json:

   json_data = json.loads("""
{


    "result":{         
        "statistics": [
                        {
                            "name": "A1",
                            "year": 1994,
                            "award": "Y1"
                        },
                        {
                            "name": "X1",
                            "year": 1990,
                            "award": "Y55"
                        }
                    ],

         "isTrue": "yes"           
            }

}""")

有没有办法返回请求中找到的所有值的键路径?

请注意,json 可以更改并具有其他结构,但路径将始终特定于 json。因此,例如,这样的事情不会起作用,因为密钥每次都不相同,硬编码不是一种选择:

json_root = json_data['result]['statistics']
json_result = [something['name'] for something in json_root]

预期结果

例如:

Path = 'result/statistics/name'

The result could be a dict like this : {'name':['A1', 'A2']}

Path2 = 'result/isTrue'

The result : {'isTrue: ['Yes']}

【问题讨论】:

    标签: python json


    【解决方案1】:

    您可以使用递归读取数据并遵循与给定路径对应的节点的函数来执行类似的操作。如果我们到达一个列表,我们只需遵循该列表所有元素中的路径:

    import json
    
    def getAllValues(data, path):
        """Get all values from data that match the given path.
        """
    
        # If the key is not in the dictionary, no element could be found
        if path[0] not in data:
            return []
        else:
            # We arrived at the end of the path, add whatever is there
            if len(path) == 1:
                return [data[path[0]]]
            else:
                # If we have a list, we want to add the values for all elements in the list
                if type(data[path[0]]) is list:
                    out = []
                    for elem in data[path[0]]:
                        out += getAllValues(elem, path[1:])
                    return out
                # If its not a list, we can just coninue on
                else:
                    return getAllValues(data[path[0]], path[1:])
    
    if __name__ == "__main__":
        data = {
            "result": {
                "statistics": [
                    {
                        "name": "A1",
                        "year": 1994,
                        "award": "Y1"
                    },
                    {
                        "name": "X1",
                        "year": 1990,
                        "award": "Y55"
                    }
                ],
                "isTrue": "yes"
            }
        }
    
        path = "result/statistics/name"
        print(getAllValues(data, path.split("/")))
    

    我得到以下输出:

    ['A1', 'X1']
    

    【讨论】:

    • 那是因为那里的路径应该是results/isTrue。 results/statistics/isTrue 不存在
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2021-05-03
    • 1970-01-01
    • 2020-12-03
    • 2018-07-01
    相关资源
    最近更新 更多