我正在使用Service Now Rest API检索服务器上的信息,该服务器将作为JSON响应返回,并将其解码为python3字典,因此我可以在代码中进一步提取特定项,但是我有难以理解如何使用从JSON创建的嵌套字典。有人可以帮我了解如何从字典中提取特定值。参见下面的示例(返回)。
#! /usr/bin/python3
# Include required libraries
import requests
# Set the request parameters
url = 'https://example.service-now.com/api/now/table/cmdb_ci_server'
user = 'example'
pwd = 'example'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)
以下是响应示例(已缩短)
{
"result": [
{
"u_raid": "",
"u_pir_required": "false",
"u_original_system": "",
"u_backup_pool": "vsdfnvjsv",
"u_virtual_ip": "",
"cpu_speed": "",
"u_vendor": "",
"u_lun_tier": "",
"cost_center": {
"link": "cdncdnckidnicsw",
"value": "vfevfdbvfdsbvsdf"
},
"dns_domain": "",
"u_vio2": "",
"fault_count": "0",
"u_hardware_type": "",
"host_name": ""
}
]
}
在阅读了一些嵌套词典教程之后,我尝试了以下方法,但是我运气不高。
print(data['result']['u_backup_pool'])
TypeError:列表索引必须是整数或切片,而不是str
答案 0 :(得分:1)
键'result'
的值是包含一项的列表(请注意方括号),请尝试print(data['result'][0]['u_backup_pool'])