如何将响应路径键保存到变量中

时间:2019-06-03 10:32:53

标签: python json

我有一个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响应。而且其中有很多数据。有时,所需的数据已经深入其中。

1 个答案:

答案 0 :(得分:1)

这可能不是最佳选择,但是我通常为此类任务编写一个辅助函数:


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') )