代码之家  ›  专栏  ›  技术社区  ›  Kaguei Nakueka

如何将JSON结果转换为Python变量?

  •  -2
  • Kaguei Nakueka  · 技术社区  · 9 年前

    我想通过Yahoo!温度API转换为Python变量。

    这是我的代码:

    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']
    

    结果如下:

    {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'}}}}
    

    我需要的信息是 +6 从…起 u'temp': u'+6' .

    如何将其引用到变量中?

    1 回复  |  直到 9 年前
        1
  •  3
  •   John    9 年前
    >>> 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'