【发布时间】:2018-05-26 10:18:16
【问题描述】:
这是 JSON 文件的内容
{
"error": {
"class": "com.attask.common.AuthenticationException",
"message": "Authentication Exception: Authentication Exception: {0}"
}
}
这是我试图解析上述内容的代码。相同的代码可以很好地解析其他 JSON 文件。但是在解析上述内容时,我收到一个错误“TypeError:字符串索引必须是整数”。
import json
fObj = open("attask1.json","r");
res = fObj.read().encode('utf-8');
fObj.close();
data = json.loads(res);
for each in data['error']:
WFErrorClass = each['class'];
WFErrorMessage = each['message'];
print WFErrorMessage;
print WFErrorClass;
请任何人解释它为什么会发生并建议我如何克服这个
非常感谢任何帮助。
Python 版本为 2.7.14
注意:缩进是完美的,没有间距错误
【问题讨论】:
-
你为什么要循环超过
data['error']?那是一个单一的字典。只需设置each = data['error']。 -
感谢 Aran-Fey,它起作用了,我得出了一个错误的逻辑来循环它。
标签: python json python-2.7