【发布时间】:2020-05-11 20:33:04
【问题描述】:
我是 python 新手。我刚开始使用 openweathermap API 进行天气 API 项目。谁能解释我哪里出错了?如何从“天气”中检索“描述”,为什么会抛出 keyerror?
我从 JSON 响应中检索“描述”的代码:
import requests
import json from pprint
import pprint
city_name= input("Enter the City name")
complete_url="https://samples.openweathermap.org/data/2.5/weather?q={},uk&appid=b6907d289e10d714a6e88b30761fae22"
+format(city_name)
response=requests.get(complete_url)
data=response.json()
pprint(response.status_code)
temprature=data['main']['temp']
windspeed=data['wind']['speed']
description=data['weather'][0]['description']
print('temprature: {}',format(temprature))
print('windspeed:{}',format(windspeed))
print('Description:{}',format(description))
我的输出是
输入城市名称西雅图 200 回溯(最近一次通话最后): 文件“/Users/suprajaraman/PycharmProjects/learnPython/venv/weather.py”,第 15 行,在 description=data['weather'][0][description] NameError: name 'description' is not defined
JSON 响应
{
"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
}
【问题讨论】:
-
好吧,标记为
wind的 JSON 对象不是数组(或带有“0” ket 的对象),所以..['wind'][0]根本不正确.
标签: python dictionary getjson keyerror openweathermap