首页 > 解决方案 > 如何将响应路径键保存到变量中

问题描述

我有一个 json 响应,其中值的路径键就像response['key1']['key2']['key3']['key4'] 我如何保存['key1']['key2']['key3']['key4']到同一个变量中以便在下一个代码中重用它?喜欢response[saved_path]或其他一些变体

例子。有一个方法:

def post_new_user response = some_code return json.loads(response.text)

结果,我收到了 json 响应。而且里面有很多数据。有时需要的数据在其中。

标签: pythonjson

解决方案


它可能不是最优的,但我通常为这些任务编写一个辅助函数:


def get_by_path(d, path):
    # recursive helper function to access the element at the desired path
    def get(d,l):
        if len(l) == 0:
            return d
        else:
            return get(d[l[0]], l[1:])
    # split the path to generate the list
    return get(d, path.split('/'))

然后,假设jsondict是您解析的 json 对象,您可以使用上述函数访问所需的路径:

jsondict = {'abc': { 'def': { 'ghi': 42 } } }
print( get_by_path(jsondict, 'abc/def/ghi') )

推荐阅读