Home > Net >  TypeError when trying to get a list of names in Pyton
TypeError when trying to get a list of names in Pyton

Time:10-12

I'm pretty new to python and I'm trying to get a list of names from an website using the following code:

This is the original code, which returns a lot of data, from which I am trying to extract the 'firstname' only

import requests

url = "https://x.gorgias.com/api/users?limit=30&order_by=name:asc&roles=agent"

headers = {
    "accept": "application/json",
    "authorization": "Basic x"
}

response = requests.get(url, headers=headers)

print(response.text)

I removed the auth key and the link since this is a code for our company. Here is the response that I get from this code:

{"data": [{"id": 602001443, "external_id": null, "active": true, "email": "[email protected]", "bio": null, "name": "Agent Name1 ", "firstname": "Agent Name1", "lastname": "", "roles": [{"id": 58506, "name": "agent"}], "role": {"id": 58506, "name": "agent"}, "created_datetime": "2022-06-01T18:14:19.081362 00:00", "updated_datetime": "2022-06-01T18:19:56.196404 00:00", "deactivated_datetime": null, "meta": {"name_set_via": "agent"}, "data": null, "has_password": true, "has_2fa_enabled": false}, {"id": 602001740, "external_id": "112351259267296708113", "active": true, "email": "[email protected]"...

What I'm trying to do is to extract the 'firstname' attribute and this is what I've did:

import requests
import json

url = "https://x.gorgias.com/api/users?limit=30&order_by=name:asc&roles=agent"

headers = {
    "accept": "application/json",
    "authorization": "Basic"
}

response = requests.get(url, headers=headers)
text = json.loads(response.text)
final_text = text['data']['firstname']

print(final_text)

But I am getting this error message:

final_text = text['data']['firstname']
TypeError: list indices must be integers or slices, not str

How can I fix this error in order for me to extract only the firstname from that list?

Thank you!

CodePudding user response:

data is a list, so you need to iterate over it

for item in text[“data”]:
    final_text=item[”firstname”]

Or text[“data”][0][“firstname”] if you need only one item in data

  • Related