You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报TypeError: string indices must be integers,如何获取JSON中的'id'值?

解决TypeError: string indices must be integers错误问题

问题原因分析

你遇到的这个错误,核心原因是**data['result']是一个字典(dictionary)而非列表(list)**。当你用for key in data['result']循环时,key实际上是字典里的键名(比如'username'、'id'这类字符串),这时再尝试key['id']就相当于用字符串去索引另一个字符串,自然会抛出TypeError。

你的原始代码

data = response.json()
print data
for key in data['result']:
    print key['id']

返回的JSON数据确认

从你打印的JSON可以明确看到result是一个字典结构:

{u'meta': {u'httpStatus': u'200 - OK', u'requestId': u'12345'}, u'result': {u'username': u'test@test.com', u'firstName': u'joe', u'lastName': u'bloggs', u'accountStatus': u'active', u'id': u'ad284hdnn'}}

修正后的代码

既然result是字典,你可以直接通过键名访问id值,不需要循环:

data = response.json()
print(data)
# 直接获取id
print(data['result']['id'])  # 输出: ad284hdnn

如果出于某些原因你需要遍历result里的所有键值对,可以用items()方法:

for key, value in data['result'].items():
    if key == 'id':
        print(value)

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:28:10