首页 > 解决方案 > JSON 数据,TypeError:字符串索引必须是整数

问题描述

我如何在代码中获得速度值?

{
  "response": {
    "speed": "1000000",
    "lastUpdated": "2018-10-09 11:19:10.981000",
    "portMode": "access",
    "portType": "Ethernet Port",
    "description": " changed by DNAC",
    "series": "Cisco Catalyst 9300 Series Switches",
    "ifIndex": "31",
    "mediaType": "100/1000/2.5G/5G/10GBaseTX",
    "className": "SwitchPort",
    "interfaceType": "Physical",
    "ipv4Address": null,
    "ipv4Mask": null,
    "isisSupport": "false",
    "mappedPhysicalInterfaceId": null,
    "mappedPhysicalInterfaceName": null,
    "nativeVlanId": "1",
    "ospfSupport": "false",
    "pid": "C9300-24UX",
    "serialNo": "FCW2140L039",
    "voiceVlan": null,
    "status": "up",
    "deviceId": "4757da48-3730-4833-86db-a0ebfbdf0009",
    "macAddress": "f8:7b:20:71:4d:98",
    "portName": "TenGigabitEthernet1/0/24",
    "adminStatus": "UP",
    "duplex": "FullDuplex",
    "vlanId": "1",
    "instanceTenantId": "5b13fcf9651f93008acd0702",
    "instanceUuid": "8beed342-3718-4fa9-8377-4c7d94c77aef",
    "id": "8beed342-3718-4fa9-8377-4c7d94c77aef"
  },
  "version": "1.0"
}

我尝试了下面的代码,但它不起作用。

for items in data["response"] print(items['speed'])

这会给我错误 TypeError: string indices must be integers

标签: pythonjsonpython-3.x

解决方案


for item in data['response']迭代一个字典。在 python 中,当你迭代一个 dict 时,你只迭代它的键。因此,每个项目都是一个字符串,因此是错误的。

在你的情况下,你可以直接写

data['response']['speed']

推荐阅读