Python json.loads TypeError:字符串索引必须是整数
下面是JSON文件的内容Python json.loads TypeError:字符串索引必须是整数,python,json,python-2.7,Python,Json,Python 2.7,下面是JSON文件的内容 { "error": { "class": "com.attask.common.AuthenticationException", "message": "Authentication Exception: Authentication Exception: {0}" } } 下面是我试图解析上述内容的代码。同样的代码在解析其他JSON文件时工作得非常好。但是在解析上述内容时,我得到了一个错误“TypeError:字符串索引必须是整数” 任何人请解释为什么会发生这种
{
"error": {
"class": "com.attask.common.AuthenticationException",
"message": "Authentication Exception: Authentication Exception: {0}"
}
}
下面是我试图解析上述内容的代码。同样的代码在解析其他JSON文件时工作得非常好。但是在解析上述内容时,我得到了一个错误“TypeError:字符串索引必须是整数”
任何人请解释为什么会发生这种情况,并建议我如何克服这一点
非常感谢您的帮助
Python版本是2.7.14
注意:缩进是完美的,间距没有错误
for each in data['error']:
请注意,data['error']
是一个dict,因此for each in data['error']
在dict上迭代,这意味着each
是dict的键,可能是“class”或“message”,无论如何,each
是一个字符串,只能由int
索引
您的json数据应该如下所示:
{
"error": [{
"class": "com.attask.common.AuthenticationException",
"message": "Authentication Exception: Authentication Exception: {0}"
}]
}
每个
在运行时不再是字典,而是字符串:
for each in data['error']:
print(each) # Returns 'class'
相反,您所需要的是:
WFErrorClass = data['error']['class'];
WFErrorMessage = data['error']['message'];
print WFErrorMessage;
print WFErrorClass;
因为
error
获取字典的第一部分,而message
/类
获取第二个值。为什么要循环数据['error']
?这是一个单独的命令。只需设置each=data['error']
。感谢Aran Fey,它起作用了,我导出了一个糟糕的逻辑来循环它。
WFErrorClass = data['error']['class'];
WFErrorMessage = data['error']['message'];
print WFErrorMessage;
print WFErrorClass;