首页 > 解决方案 > 从 http 响应中获取特定值

问题描述

我正在使用requests库来查询 F5 Big IP。我得到了虚拟服务器的列表。我需要做一个循环来(VS1, VS2, VS3)从响应中获取每个 VS 名称,以便在另一个请求中使用,例如

https://localhost/mgmt/tm/ltm/virtual/VS1

什么代码将从响应中获取每个名称值?我试过这个,但无法让它工作。

url = "https://bigipname.domain.local/mgmt/tm/ltm/virtual"
querystring = {"$select":"name"}
headers = {
    'Content-Type': "application/json",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Host': "bigipgname.domain.local",
    'accept-encoding': "gzip, deflate",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }
response = requests.request("GET", url, headers=headers, params=querystring, verify=False)

我得到以下 json 格式的响应:

{'kind': 'tm:ltm:virtual:virtualcollectionstate', 'selfLink': 'https://localhost/mgmt/tm/ltm/virtual?$select=name&ver=13.1.1.2', 'items': [{'name': 'VS1'}, {'name': 'VS2'}, {'name': 'VS3'}]}

任何帮助表示赞赏。谢谢

标签: pythonpython-requests

解决方案


您可以使用列表推导来提取“项目”。

new_list = [item["name"] for item in response["items"]]

推荐阅读