Reputation: 23
I have tried this easy value parsing but it did not work. I am able to get all response and if there is single value I can easily get value but I could not catch why I am getting this error.
TypeError: list indices must be integers or slices, not str
I want to get all "id" from this JSON response.
Here is my code:
def get_api_all(api):
r = requests.get(f'{base_url}/{api}/')
return r.status_code, r.json()
def test_get_person(self):
status_code, data =get_api_all('persons')
ids = []
for i in data['id']:
print(i['id'])
and here is my sample response in json format:
[
{
"id":"b9f2d28c-57dc-4381-a752-ac36611ab51a",
"first_name":"Arnold",
"last_name":"Schwarzenegger",
"birth_year":1947
},
{
"id":"b636e887-7402-4eda-885f-549ea9792116",
"first_name":"Charlize",
"last_name":"Theron",
"birth_year":1975
},
{
"id":"c22c7475-bd4b-4dfd-ab3b-eb27ef4cb59f",
"first_name":"Brad",
"last_name":"Pitt",
"birth_year":1963
},
{
"id":"33c22f9d-cfc4-4733-986a-61e1a73cee8e",
"first_name":"Patrick",
"last_name":"Stewart",
"birth_year":1940
},
{
"id":"a0c54b47-35b1-4894-bccf-7bac9ade8f41",
"first_name":"dumm",
"last_name":"Stewart",
"birth_year":1940
},
{
"id":"a43fca0c-2a49-49be-902f-ec48ac4b57cb",
"first_name":"Patrick",
"last_name":"Stewart",
"birth_year":1940
} ]
Upvotes: 1
Views: 1786
Reputation: 9197
You have a mistake there:
for i in data['id']:
print(i['id'])
should be:
for i in data:
print(i['id'])
because data is a list of dictionaries, not a dictionary. A list has no key, therefore data['id']
raises an error.
Upvotes: 1