【发布时间】:2023-04-03 19:49:01
【问题描述】:
我正在使用 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
【问题讨论】:
标签: python json dictionary