【问题标题】:Having trouble with nested Python3 dictionary [duplicate]嵌套 Python3 字典遇到问题 [重复]
【发布时间】: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


    【解决方案1】:

    'result' 键的值是一个包含一个项目的列表(注意方括号),试试print(data['result'][0]['u_backup_pool'])

    【讨论】:

    • 谢谢!现在我明白了!
    • @Atomiklan 请注意,由于它是一个列表,这表明其中可能有 多个 dict(甚至可能没有)。您可能应该使用for .. in ..... 在列表中循环
    • 感谢您的帮助。现在我明白了发生了什么,这更有意义。
    猜你喜欢
    • 2018-08-02
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多