Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python json.loads TypeError:字符串索引必须是整数_Python_Json_Python 2.7 - Fatal编程技术网

Python json.loads TypeError:字符串索引必须是整数

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:字符串索引必须是整数” 任何人请解释为什么会发生这种

下面是JSON文件的内容

{
"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;