解析 Openweather API Python

Parsing Openweather API Python

好的,我遇到了一些情况,在理解如何从 JSON returned 中提取值时遇到了障碍 API .我有以下代码:

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)

这将 return 一长串 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)

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

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

但我觉得目前我的方向不对,如果有人能提供一些建议,我将不胜感激。

所以,我做了一些事情来使它变得更好,我已经实施了 @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():

我能够 return 返回我需要的东西。

我写了一个小函数来从 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"])