Python 2.7解析JSON遇TypeError: string indices must be integers问题求助
问题分析与解决方法
嘿,我来帮你拆解下这个报错的原因和解决办法!
为什么会报错?
先看看你要解析的JSON结构:
{ "error": { "class": "com.attask.common.AuthenticationException", "message": "Authentication Exception: Authentication Exception: {0}" } }
这里的error对应的是单个字典对象,不是数组(数组会用[]包裹)。但你代码里写了for each in data['error']:——在Python 2.7里遍历字典的话,默认是遍历它的键(也就是'class'和'message'这两个字符串),这时候each是字符串类型,你再写each['class']就会触发TypeError: string indices must be integers,因为字符串只能用数字当索引(比如each[0]),不能用字符串哦。
怎么解决?
既然error是单个对象,完全不需要循环,直接访问它的属性就行:
修改后的代码:
import json fObj = open("attask1.json","r") res = fObj.read().encode('utf-8') fObj.close() data = json.loads(res) # 直接读取error对象里的字段,不用循环 WFErrorClass = data['error']['class'] WFErrorMessage = data['error']['message'] print WFErrorMessage print WFErrorClass
另外推荐用with语句处理文件,它会自动帮你关闭文件,代码更简洁安全:
import json with open("attask1.json","r") as fObj: res = fObj.read().encode('utf-8') data = json.loads(res) WFErrorClass = data['error']['class'] WFErrorMessage = data['error']['message'] print WFErrorMessage print WFErrorClass
小补充
如果你的业务场景里error有时候会是数组(比如返回多个错误信息),那才需要循环遍历,但当前这个JSON里error是单个字典,直接取值就够啦~
内容的提问来源于stack exchange,提问作者user1289569
相关产品推荐
相关产品推荐

