如何使用python从json格式的键中提取值

时间:2019-08-29 15:32:11

标签: python json

我的JSON响应如下:

[{"interface":"WAN 1","status":"Active","ip":"192.168.254.3","gateway":"192.168.254.1","publicIp":"206.59.240.69","dns":"192.168.254.1","vlan":2,"usingStaticIp":false}]

我想提取“状态”的值,但出现以下错误:

TypeError: 'Response' object has no attribute '__getitem__'

代码段:

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
print(response["status"])

有人可以帮我提取'status'的值吗?

1 个答案:

答案 0 :(得分:1)

您需要先加载JSON:

import json

response = requests.request("GET", url, headers=headers, params=querystring)
data = json.loads(response.text)
print(data["status"])

请注意,根据提供的JSON响应示例,响应是一个列表,在这种情况下,您将必须打印data[0]["status"]