【问题标题】:How to get weather from openWeahter如何从 openWeather 获取天气
【发布时间】:2017-10-23 14:56:19
【问题描述】:

我对 Json 非常陌生,Phyton。但我试图创建自己的天气应用程序。 我无法从这个 Jsonobject 中获取天气信息。

这是 Jsonobject 的样子:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}

这是我的代码:

@app.route('/temperatuur', methods=['GET','POST',])
def temperatuur():
    zipcode = request.form['zip']
    r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',be&APPID=84c7d83bae2f2396ebd3a4a48dfdd057')
    json_object = r.json()
    weer = json_object['weather',[1]]
    temp_k = int(json_object['main']['temp'])
    temp_c = (temp_k - 273)
    plaats = str(json_object['name'])
    return render_template('temperatuur.html', temperatuur=temp_c, plaats = plaats, weer = weer)

这是错误:

ypeError: unhashable type: 'list'

【问题讨论】:

标签: python json flask


【解决方案1】:

我认为这是你做错的地方

weer = json_object['weather',[1]]

把它改成:

weer = json_object['weather'][0]

另外,我认为您的 json 数据中没有数据对象“名称”plaats = str(json_object['name'])

【讨论】:

    【解决方案2】:

    在您的上述请求中,您尝试使用超出范围的索引(即 [1])访问列表,而您必须使用 [0]:

    def temperatuur():
        zipcode = '10024'
        r = requests.get('http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+'&APPID=84c7d83bae2f2396ebd3a4a48dfdd057')
        json_object = r.json()
        weer = json_object['weather'][0]
        temp_k = int(json_object['main']['temp'])
        temp_c = (temp_k - 273)
        plaats = str(json_object['name'])
        return render_template('temperatuur.html', temperatuur=temp_c, plaats = plaats, weer = weer)
    

    相信你会得到想要的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2020-03-16
      • 2020-12-16
      • 1970-01-01
      • 2011-10-27
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多