python - 解析 Openweather API Python

标签 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

但我觉得我目前没有走上正确的道路,如果有人可以提供一些建议,我将非常感激。

最佳答案

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

我能够通过这个返回我需要的东西。

关于python - 解析 Openweather API Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101757/

相关文章:

json - 无法在 Grails 2.1 中的 ExtJS 网格 (4.2.1) 中填充 JSON 数据

java - Jackson SAX 解析器在解析巨大的 JSON 时抛出异常

java - 如何在Android中单独显示openweather map 数据?

javascript - React - 使用用户输入进行 API 调用的正确方法是什么?

python - Python 中的系统 vs 调用 vs popen

c# - 如何将具有索引引用的 JSON 数据反序列化为强类型 C# 对象?

python - 如何将自定义 Django 用户模型注册到管理页面?

javascript - OpenWeatherMap.ORG API - $.get JSON 不起作用,我没有收到任何数据

python - 将函数应用于 Pandas Groupby

python - 如何查找二维数组的按列唯一元素及其频率