【问题标题】:json.loads TypeError: string indices must be integersjson.loads TypeError:字符串索引必须是整数
【发布时间】: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


【解决方案1】:

each 在运行时不再是字典而是字符串:

for each in data['error']:

    print(each) # Returns 'class'

您只需要:

WFErrorClass = data['error']['class'];
WFErrorMessage = data['error']['message'];
print WFErrorMessage;
print WFErrorClass;

因为error 获取字典的第一部分,message/class 获取第二个值。

【讨论】:

    【解决方案2】:
    for each in data['error']:  
    

    注意data['error']是一个dict,所以for each in data['error']是在一个dict上迭代,这意味着each是dict的key,可能是“class”或者“message”,反正each是一个字符串,只能被int索引。

    你的 json 数据应该是这样的:

    {
    "error": [{
    "class": "com.attask.common.AuthenticationException",
    "message": "Authentication Exception: Authentication Exception: {0}"
    }]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2021-04-28
      • 2020-06-24
      • 2016-03-26
      • 2017-09-07
      • 2018-08-19
      • 2016-02-17
      相关资源
      最近更新 更多