The “list indices must be integers or slices, not str” error is a little obtuse sounding, but it actually quite simply if you know what’s going on. In python a list looks like this:
my_list = ['a', 'b', 'c']
It has an implicit order to its items, and each one receives an index 0, 1, 2, but the items are not named in any way so they can only be referred to either by their index or a “slice” which is a way of expressing a group of indexes. IE this will work:
>>> my_list = ['a', 'b', 'c']
>>> my_list[0]
'a'
But this will not:
>>> my_list = ['a', 'b', 'c']
>>> my_list['0']
And neither will this:
>>> my_list = ['a', 'b', 'c']
>>> my_list['blahblah']
Because ‘0’ and ‘blahblah’ are both strings. You might just as well be asking “get me number b” which makes no sense!
This is not to be confused with dictionaries, which have a “key” you can reference by name:
>>> my_list = {'0': 'monkey', 'blahblah': 'badger'}
>>> my_list['0']
'monkey'
>>> my_list['blahblah']
'badger'
So, TLDR: The error is just a really obtuse way of saying “you need a number to get the value of something form a list”
No doubt your json_data['0']
should read json_data[0]
It’s always good practise to do this kind of stuff in a Python repl (just run Python at the command line) so you can step through your code piece by piece and play with the json_data
object to see what it contains.
In your repl you might:
>>> import urllib.parse
>>> import requests
>>> data = requests.get('your HTTP url').json()
>>> print(json)
... shows what's returned
>>> json['0']
... returns an error
>>> json[0]
... shows the first element
>>> dir(json)
... returns a list of methods on `json`
This makes it easy to prod and poke at something exploratively, and while you’ll still see errors raised, they wont abort the repl so you can continue prodding and poking until you learn what’s what, and then go and bake that into your .py
file.