简体   繁体   English

TypeError:字符串索引必须是带有.json()字典的整数

[英]TypeError: string indices must be integers with .json() dictionary

I am trying to access a dictionary key and value, but getting TypeError: string indices must be integers error when doing so. 我正在尝试访问字典键和值,但执行TypeError:这样做时字符串索引必须是整数错误。

The code below I am using.. 我正在使用以下代码。

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

The response I get.. *Note: I formatted the dict output here for readability. 我得到的响应.. *注意:我在这里格式化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

The goal is to obtain the email. 目的是获取电子邮件。 I'm thinking the unicode character in front of the key is messing some things up too, but haven't been able to find anything on that yet. 我认为键前面的unicode字符也弄乱了一些东西,但是还没有找到任何东西。 Why is this not working? 为什么这不起作用?

for x in resource.json():

Here what you are doing is looping over each entry in the dictionary and assigning the key to x. 在这里,您要做的是遍历字典中的每个条目并将键分配给x。 So for example, in the first iteration of the for loop, 因此,例如,在for循环的第一次迭代中,

x = "public_repo"

This is why you see "p" and "i" being printed for x[0] and x[4] since they are the 0th and 4th position of the string "public_repo", respectively. 这就是为什么您看到为x [0]和x [4]打印“ p”和“ i”的原因,因为它们分别是字符串“ public_repo”的第0和第4位。

What you want to do instead is assign resource.json() to a variable and simply index into that. 相反,您要做的是将resource.json()分配给变量,然后简单地将其索引。 For example, 例如,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM