d_rooney
d_rooney

Reputation: 89

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.

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.

<type 'dict'>
{
    u'public_repos': 1, 
    u'site_admin': False,  
    u'gravatar_id': u'', 
    u'hireable': None, 
    u'id': 6048,  
    u'email': u'[email protected]'
}
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. Why is this not working?

Upvotes: 0

Views: 926

Answers (1)

Kent Shikama
Kent Shikama

Reputation: 4060

for x in resource.json():

Here what you are doing is looping over each entry in the dictionary and assigning the key to x. So for example, in the first iteration of the for loop,

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.

What you want to do instead is assign resource.json() to a variable and simply index into that. For example,

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

Upvotes: 4

Related Questions