Search code examples
pythondictionarytwitch

Accessing nested values in JSON data from Twitch API


I am using the code:

getSource = requests.get("https://api.twitch.tv/kraken/streams")
text = json.loads(getSource.text)
print text["streams"]["_links"]["_self"]

text is a dictionary that I get by calling json.loads. I then try to get the nested values, eventually trying to get the url but this error shows up:

Traceback (most recent call last):
  File "Twitch Strim.py", line 11, in <module>
    print text["streams"]["_links"]["_self"]
TypeError: list indices must be integers, not str

How can I correct this?


Solution

  • You are accessing the json data wrong, the correct way of accessing this would be:

    print text["streams"][0]["_links"]["self"]
    

    Full code:

    >>> import requests
    >>> import json
    >>> getSource = requests.get("https://api.twitch.tv/kraken/streams")
    >>> text = json.loads(getSource.text)
    >>> print text["streams"][0]["_links"]["self"]
    https://api.twitch.tv/kraken/streams/summit1g
    >>> print text["streams"][1]["_links"]["self"]
    https://api.twitch.tv/kraken/streams/tsm_theoddone
    >>> print text["streams"][2]["_links"]["self"]
    https://api.twitch.tv/kraken/streams/reynad27
    

    Note that text["streams"] provides you a list of items (and not a dict), so you will have to access by its index values.

    You can check the same using

    >>> type(text["streams"])
    <type 'list'>