Search code examples
pythonurllib

Get data from Json response from urllib using python


I am getting data from an API call using the following Python code.

import urllib.request
import json

response = urllib.request.urlopen(req)
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj) 

The result set is as below:

{"forecast": [645.946539419183], "index": [{"Date": 1629072000000, "ProductType": "Type1"}]}

How can I just return the forecast value?

645.946539419183

I have tried many things to get the value but nothing seems to be working

print(json_obj['forecast'][0]) 

Throws the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-44-af91dd9fcc96> in <module>
     37     json_obj = json.loads(string)
     38 
---> 39     print(json_obj['forecast'][0])
     40 
     41 except urllib.error.HTTPError as error:

TypeError: string indices must be integers

Solution

  • json_obj = json.loads(json.loads(string))
    json_obj["forecast"][0]
    

    The second indexing is required because the value you seek is in a list.

    This works, but I want to stress out that there is probably a bug in the service that provides the string, since it encoded twice the data...