python - 如何将响应路径键保存到变量中
问题描述
我有一个 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 响应。而且里面有很多数据。有时需要的数据在其中。
解决方案
它可能不是最优的,但我通常为这些任务编写一个辅助函数:
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') )
推荐阅读
- android - Web Worker 是在主 ui android 线程还是单独的线程上运行?
- amazon-web-services - 无法删除 S3 对象,“拒绝访问”
- wix - 在 WinpE 中运行 Wix MSI 安装
- azure - Spring Boot OAuth2 和 Azure AD
- javascript - 使用 sessionStorage 在页面刷新时保持子菜单显示
- python - 如何将卷积层添加到自定义估计器
- javascript - 仅 Firefox 中的 Javascript 参考错误
- regex - 每行最后两个报价的正则表达式
- javascript - 如何清空对象(对象字段可以变化和动态)
- cassandra - 如何在 cassandra 中设置分区键?