【问题标题】:TypeError: string indices must be integers with .json() dictionaryTypeError:字符串索引必须是带有 .json() 字典的整数
【发布时间】:2018-05-15 05:22:24
【问题描述】:

我正在尝试访问字典键和值,但这样做时出现 TypeError: string indices must be integers 错误。

我正在使用下面的代码..

def function():
    EMAILS_FOR_ISSUES = 'https://github.com/api/v3/users/JimmyBuffet'
    resource = requests.get(EMAILS_FOR_ISSUES, auth=AUTH)
    if not resource.status_code == 200:
        raise Exception(resource.status_code)

    print(type(resource.json()))
    print(resource.json())
    for x in resource.json():
        print(x)
        print(x[0])
        print(x[4])
        user_email = x['email']
        print(user_email)
return

我得到的响应.. *注意:为了便于阅读,我在此处格式化了 dict 输出。

<type 'dict'>
{
    u'public_repos': 1, 
    u'site_admin': False,  
    u'gravatar_id': u'', 
    u'hireable': None, 
    u'id': 6048,  
    u'email': u'jbuffet@xyzxyz.com'
}
public_repos
p
i
Traceback (most recent call last):
  File "retrieve_old_issues.py", line 122, in <module>
    function()
  File "retrieve_old_issues.py", line 58, in function
    user_email = x['email']
TypeError: string indices must be integers

目标是获取电子邮件。我在想钥匙前面的 unicode 字符也搞砸了一些事情,但还没有找到任何东西。为什么这不起作用?

【问题讨论】:

    标签: python json rest dictionary


    【解决方案1】:
    for x in resource.json():
    

    在这里,您正在做的是遍历字典中的每个条目并将键分配给 x。例如,在 for 循环的第一次迭代中,

    x = "public_repo"
    

    这就是为什么您会看到 x[0] 和 x[4] 打印“p”和“i”的原因,因为它们分别是字符串“public_repo”的第 0 位和第 4 位。

    您想要做的是将 resource.json() 分配给一个变量并简单地对其进行索引。例如,

    dict = resource.json()
    print(dict["email"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      相关资源
      最近更新 更多