1

I am currently trying to parse some data from a get request response and I keep getting this error: "TypeError: list indices must be integers or slices, not str"

it would be great, if anybody could help me out what i am trying to solve. thank you so much in advance.

import requests
import json


class userList(APIView):
    def get(self,request,format=None):

        user_data = []
        url = 'https://reqres.in/api/users?page=1'

        try:
            r = requests.get(url).json()
            user = {
                'id': r['data']['id'],
                'email': r['data']['email']
            }
            user_data.append(user)
            return Response({"user_data":user_data}, status=status.HTTP_200_OK)


{
data:{

0:{
'id'    : 1
'email' :   "[email protected]"
'first_name' :  "George"
'last_name' :   "Bluth"
'avatar' :  "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
}

1:{
'id'    : 2
'email' :   "[email protected]"
'first_name' :  "apdas"
'last_name' :   "loanz"
'avatar' :  "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
}

2:{
'id'    : 3
'email' :   "[email protected]"
'first_name' :  "joan"
'last_name' :   "homli"
'avatar' :  "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
}
}
}

6
  • Could you please post a traceback? Commented May 2, 2020 at 4:23
  • Is data a dictionary of a list? Separate each x[y] into it's own line so you can see which is causing the error, i suspect you need r[0]['data']['id'] Commented May 2, 2020 at 4:23
  • What line is flagged in the traceback. (You should include the traceback in your question.) Commented May 2, 2020 at 4:24
  • Inspect r['data'] and check if it has a list instead of a dict. In a quick look here at your json content I think that the correct is use r['data'][someIndex]['id'] for example. You should be use something like r['data'][0]['id'] Commented May 2, 2020 at 4:24
  • i am getting one value. Instead of adding [0], is it possible that iterate through results in case there is more than one result. @GeekSilva Commented May 2, 2020 at 4:32

1 Answer 1

1

Try this:

user_data = [{'id': x['id'], 'email': x['email']} for x in r['data']]

Output:

[{'id': 1, 'email': '[email protected]'}, {'id': 2, 'email': '[email protected]'}, {'id': 3, 'email': '[email protected]'}]
Sign up to request clarification or add additional context in comments.

4 Comments

TypeError: list indices must be integers or slices, not dict
here , for x in r['data']
i didn't get what you mean
@xxnora the json you posted is not same as json you are getting from the url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.