python3 报错TypeError: string indices must be integers

这篇博客探讨了一个常见的编程问题,即在尝试访问JSON响应时遇到的TypeError。作者指出,错误的原因在于直接尝试用字符串索引访问数据,而没有先将JSON转换为Python可以理解的格式。为了解决这个问题,他们建议使用`json.loads()`函数将JSON字符串转换为字典,然后可以正常地通过键来访问数据。这个简单的修复方法可以避免类似错误,提高代码的健壮性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错提示

Traceback (most recent call last):
  File "E:\kc.py", line 27, in <module>
    s_rep_result = s_rep['resultSet']
TypeError: string indices must be integers

原因分析

JSON格式导致的错误:

s_rep = client.service.callWebService(serviceName=s_name, userName=userName, password=s_pass, param='')
s_rep_result = s_rep['resultSet']

由于获取(s_rep)是json数据,所以要json.loads(),才能把json格式转为python识别的格式

代码改为:

s_rep = client.service.callWebService(serviceName=s_name, userName=userName, password=s_pass, param='')
s_rep_result = json.loads(s_rep).['resultSet']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值