Skip to main content
 首页 » 编程设计

Python 和 JSON 错误之TypeError : string indices must be integers

2024年10月24日7lvdongjie

我在解析 JSON 响应时收到错误 TypeError: string indices must be integers。我看不出我做错了什么,响应是一本字典..

我的代码示例从可测试的免费 REST API 中得到相同的错误:

import requests 
 
response = requests.get('http://services.groupkt.com/state/get/IND/all') 
 
for states in response.json(): 
    print ('{} {}'.format(states['name'], states['capital'])) 

请您参考如下方法:

当你遍历一个字典时,你就是在遍历它的键。该字典的(唯一)顶级键是“RestResponse”,您的代码转换为:“RestResponse”[“name”]。由于它是一个字符串,Python 需要整数索引(例如用于切片的“RestResponse”[3])。

如果您调查结果字典的结构,您会发现您想要的结果位于 response.json()["RestResponse"]["result"] 下:

for states in response.json()["RestResponse"]["result"]: 
    print ('{} {}'.format(states['name'], states['capital'])) 

输出:

Andhra Pradesh Hyderabad, India 
Arunachal Pradesh Itanagar 
Assam Dispur 
Bihar Patna 
Chhattisgarh Raipur 
...