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

标签 python json rest

我在解析 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
...

关于Python 和 JSON 错误 - TypeError : string indices must be integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972522/

相关文章:

python - 使用python循环将数据插入sql表

python - 如何通过继承扩展 init 方法

ios - 在 Swift 4 中使用对象映射器解析嵌套对象

json - 使用 json 的 FOSRest Symfony POST

html - 通过 app.post 呈现的页面出现 `Confirm Form Resubmission` 问题( '/' ,在expressjs中

python - 创建字典,其中列表项作为键,列表项出现的次数作为值

c# - 如何拥有一个带有 json 动态成员的 WCF DataContract

javascript - Angular/Ionic 通过 REST 服务在导入的 HTML 中隐藏数据属性(data-***)

c# - 使用 RESTSHARP 的 OAuth 2 身份验证不起作用

python - 在 Mac 上的 Docker 中运行 Keras 时出现内存问题