解析Openweather API Python

时间:2017-03-29 18:48:44

标签: python json openweathermap

好的,我遇到了一些情况,我已经遇到了解决如何从API返回的JSON中提取值的障碍。我有以下代码:

import requests
import json

weather_results = []
key = 'somekey'
cities = ['sometown']

def weather_get(apikey, city):
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
    return(r.text)

这将返回一个长字符串的JSON格式,如下所示:

[u'{"coord":{"lon":-73.59,"lat":45.51},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":277.5,"pressure":1022,"humidity":55,"temp_min":277.15,"temp_max":278.15},"visibility":24140,"wind":{"speed":3.1,"deg":300},"clouds":{"all":90},"dt":1490810400,"sys":{"type":1,"id":3829,"message":0.0973,"country":"CA","sunrise":1490783901,"sunset":1490829598},"id":6077243,"name":"Montreal","cod":200}']

现在,如果我写一个像这样的功能:

def get_temp_min(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['main'].items():
        if key=='temp_min':
            return(value)

它将返回以下值,但如果我尝试:

def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data['weather'].items():
      if key=='description':
          return(value)

我没有收到我想要的回复类型。我尝试过这样的事情,看看我是否可以深入了解JSON:

def get_weather_description(arg):
for items in arg:
    data = json.loads(items)
    for key, value in data.items():
        if key=='weather':
            data2= value
            for items in data2:
                data3 = items

但是我觉得我现在没有走上正轨,如果有人能提供一些建议,我真的很感激。

2 个答案:

答案 0 :(得分:1)

所以,我已经做了一些事情来改善这一点,我已经实现了@ kiran.kodur的建议

def weather_get(apikey, city):
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q={},canada&APPID={}'.format(city, apikey))
return(r.json())

'return(r.json())'使代码更清晰:

def get_temp(arg):
for items in arg:
    for key, value in items['main'].items():
        if key=='temp':
            return(value)
def get_pressure(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='pressure':
                return(value)
def get_temp_min(arg):
    for items in arg:
        for key, value in items['main'].items():
            if key=='temp_min':
                return(value)

事实证明我需要修改:

for key, value in data.items()

致:

for key, value in items['weather'][0].items():

我能够用这个回复我需要的东西。

答案 1 :(得分:0)

我写了一个小函数来从openweatherdata提供的天气数据中获取所需的信息。

def get_value_from_dictionary(dic, keys):
    if type(dic)is dict: #check if dic is a dictionary
        if len(keys)==1:
            value=dic.get(keys[0])
        else:
            dic=dic.get(keys[0])
            value=get_value_from_dictionary(dic,keys[1:])
    elif type(dic)is type(None): #if dic is None
        value=None
    elseif type(dic) is list: #if dic is a list
        dic=dic[keys[0]]
        value=get_value_from_dictionary(dic,keys[1:])
    return value

此功能反复遍历给定的字典,直到找到您感兴趣的最终键。

这可以通过使用ParanoidsPenguin定义来调用:

weather = weather_get({'yourapikey'}, {'yourcity'})
current_weather_description = get_value_from_dictionary(weather,["weather",0,"description"])
current_snow_1h=get_value_from_dictionary(x,["snow", "1h"])