尝试从JSON获取数据时出现KeyError:0

2021-12-08 05:04:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。我刚开始使用OpenWeatherMapAPI做一个天气API项目。有人能解释一下我哪里出了问题吗?如何从“天气”中检索“描述”以及它为什么抛出keyrerror

从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=数据['weather'][0]['description']

print('temprature: {}',format(temprature)) 

print('windspeed:{}',format(windspeed))
print('Description:{}',format(description))

我的输出是

Enter the City name seattle 200 Traceback (most recent call last): File "/Users/suprajaraman/PycharmProjects/learnPython/venv/weather.py", line 15, in 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
}