Why am I getting an IndexError for a (seemingly) properly-split string?
Question: I currently have a script that is supposed to fetch and return the number of
clicks a Bit.ly link has. I start out by gathering and reading the data from a
Bitly url, which I appear to be doing correctly.

    
    
        bitly_data = "https://api-ssl.bitly.com/v3/link/clicks?access_token=ACCESS_TOKEN&link=http://bit.ly/"+link
        src = urllib2.urlopen(bitly_data)
        src = src.read()
    

When `link` is something such as `TY8lnd`, `src` is a string that looks
something like

> {"status_code": 200, "data": {"units": -1, "tz_offset": -4, "unit": "day",
> "link_clicks": 535}, "status_txt": "OK"}

I now want to parse this string to get just the numerical value after
`link_clicks`. I figured the best way to do this was by making two splits.

    
    
        src=src.split('clicks": ')
        src = str(src[1])
        clicks = src.split('}, "status')
        clicks = clicks[0]
    

When I run this, clicks does, ultimately, equal the correct number and only
that. However, Terminal returns an IndexError for the line `src =
str(src[1])`. I tried getting rid of the `str()` but this had no effect. An
understanding as to why I am getting this error despite the end value being
corrected would be greatly appreciated.

Here is the Traceback in its entirety:

    
    
    Traceback (most recent call last):
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1701, in __call__
        return self.wsgi_app(environ, start_response)
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1689, in wsgi_app
        response = self.make_response(self.handle_exception(e))
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1687, in wsgi_app
        response = self.full_dispatch_request()
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1360, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1358, in full_dispatch_request
        rv = self.dispatch_request()
      File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1344, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "/Users/Zach/Dropbox/bitly/bit.py", line 35, in settings
        src = str(src[1])
    IndexError: list index out of range
    

Thank you in advance.


Answer: This response is json, as such, decode the json instead of trying to parse the
string.

    
    
    >>> import json
    >>> resp = '{"status_code": 200, "data": {"units": -1, "tz_offset": -4, "unit": "day", "link_clicks": 535}, "status_txt": "OK"}'
    >>> resp_object = json.loads(resp)
    >>> resp_object and resp_object.get('data', {}).get('link_clicks', 0) or 0
    535
    

