I'm trying to for loop through a json data and only look at "deadline_time" key. But I don't seem to know how to do that!
Here's my code:
import json
from urllib.request import urlopen
with urlopen("https://fantasy.premierleague.com/api/bootstrap-static/") as response:
source = response.read()
data = json.loads(source)
print(json.dumps(data, indent=2))
for item in data['events']['deadline_time']:
print(item)
Here's what the API looks like:
{
"events": [
{
"id": 1,
"name": "Gameweek 1",
------> "deadline_time": "2021年08月13日T17:30:00Z",
"average_entry_score": 69,
"finished": true,
"data_checked": true,
"highest_scoring_entry": 5059647,
"deadline_time_epoch": 1628875800,
"deadline_time_game_offset": 0,
"highest_score": 150,
"is_previous": true,
"is_current": false,
"is_next": false,
...
But I end up getting this error:
File "API2.py", line 11, in <module>
for item in data['events']['deadline_time']:
TypeError: list indices must be integers or slices, not str
asked Aug 24, 2021 at 15:53
3 Answers 3
You need to loop through the events not the individual deadline time.
Replace
for item in data['events']['deadline_time']:
print(item)
With
for item in data['events']:
print(item['deadline_time'])
answered Aug 24, 2021 at 15:56
data['events']['deadline_time']
gives you the value of deadline_time
and it's string
Replace it like this:
for item in data['events']:
print(item['deadline_time'])
answered Aug 24, 2021 at 15:58
The right way to achieve this
for item in data['events']:
print(item["deadline_time"])
answered Aug 24, 2021 at 16:07
lang-py