Search code examples
pythonjsonyahoo-api

How to get a JSON result into a Python variable?


I would like to get the temperature via Yahoo! temperature API into a Python variable.

This is my code:

import urllib2, urllib, json
baseurl = "https://query.yahooapis.com/v1/public/yql?"
yql_query = "select item.condition from weather.forecast where woeid = 35252 and u='c'"
yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json"
result = urllib2.urlopen(yql_url).read()
data = json.loads(result)
print data['query']['results']

Those are the results:

{u'channel': {u'item': {u'condition': {u'date': u'Sun, 17 Jan 2016 3:50 am CET', u'text': u'Light Snow', u'code': u'14', u'temp': u'+6'}}}}

The piece of information I need is the +6 from u'temp': u'+6'.

How can I reference it into a variable?


Solution

  • >>> d = {u'channel': {u'item': {u'condition': {u'date': u'Sun, 17 Jan 2016 3:50 am CET', u'text': u'Light Snow', u'code': u'14', u'temp': u'+6'}}}}
    >>> temp = d['channel']['item']['condition']['temp']
    >>> print temp
    u'+6'