Skip to main content
 首页 » 编程设计

python json嵌套字典和列表解码

2025年05月04日16davidwang456

我正在尝试解析 API 调用的输出,这是一个带有嵌套字典和列表的 json 对象,深度未知。我看到了几个递归函数从嵌套列表/字典中获取键值的示例,但我也想获得特定的顺序以及结构的正确性。例如:

    response = {'a': {'b': {'b1': 1, 'b2': 2}, 
                'c': [{'c1': 3,'c2': [{'x':55,'y':56},{'x':65,'y':66}]}, 
                      {'c1': 5,'c2': [{'x':75,'y':76},{'x':85,'y':86}]}] 
                   } 
                 } 
 
fun(response,"a-c-c2-x") should return [55,65,75,85] 
fun(response,"a-b-b2") should return [2] 
fun(response,"a-b2-b") should return [] 

到目前为止,我所拥有的是行不通的:)

def get_response_values(response=None, key=None, result=None): 
    print("1-r: {} - key: {} -r:{}".format(response, key, result)) 
    if result is None: 
        result = [] 
 
    if '-' in key: 
        if isinstance(response, dict): 
            index = key.find('-') 
            response = response[key[:index]] 
            key = key[index+1:] 
            print("3-r: {} - key: {} -r:{}".format(response, key, result)) 
            get_response_values(response, key, result) 
 
        if isinstance(response, list): 
            index = key.find('-') 
            key = key[index+1:] 
            for item in response: 
                print("4-r: {} - key: {} -r:{}".format(item, key, result)) 
                get_response_values(item, key, result) 
 
    else: 
        try: 
            result.append(response[key]) 
            print("2-r: {} - key: {} -r:{}".format(response, key, result)) 
            return result 
        except: 
            print("5-r: {} - key: {} -r:{}".format(response, key, result)) 
            return result 
 
 
    return result 

请您参考如下方法:

您可以使用像 jsonselect 这样的库它实现了 JSON Select查询规范语言。

基本程序示例:

from jsonselect import select 
 
result = select(query, data) 

更新:或者看起来您也可以使用 funcy 的 funcy.get_in()功能。

不要重新发明轮子;有很多现成可用的解决方案。

更新#2:鉴于您在下方的评论,这里是一个更易于理解和阅读的示例,它将帮助您完成 80% 的工作(不使用递归,递归有失败的风险堆栈!):

def query(data, path): 
    elem = data 
    try: 
        for x in path.strip("/").split("/"): 
            elem = elem.get(x) 
    except: 
        pass 
 
    return elem