python - 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
解决方案
for item in data['response']
迭代一个字典。在 python 中,当你迭代一个 dict 时,你只迭代它的键。因此,每个项目都是一个字符串,因此是错误的。
在你的情况下,你可以直接写
data['response']['speed']
推荐阅读
- typescript - React Navigation - VSCode 中的 RootStackParamList 错误
- r - 如何将米转换为R中的十进制坐标?
- python - 使用 Flask 更新 HTML 页面
- pgadmin-4 - 已安装 pgadmin4 但没有 setup-web.sh 文件或 pgadmin4 目录
- html - 如何关闭 HTML 中输入字段的预填充?
- javascript - 使用反应交叉观察器将标题颜色从透明更改为白色
- git - 强制分支成为主人
- c# - 这行代码中的“_id”是什么意思?
- javascript - Twitter-Bootstrap 5 轮播指示器和控件不起作用。为什么?
- api - 无法显示子回收站视图