KeyError: 0 при попытке получить данные из JSON - PullRequest
0 голосов
/ 26 января 2020

Я новичок в python. Я только начал работать над проектом API погоды с использованием openweathermap API. Кто-нибудь может объяснить, где я ошибаюсь? Как извлечь «описание» из «погоды» и почему он генерирует ключевую ошибку?

Мой код для получения «описания» из ответа 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))

Мой вывод

Введите название города seattle 200 Traceback (последний вызов был последним): Файл "/ Users / suprajaraman / PycharmProjects / learnPython / venv / weather.py ", строка 15, в описании = data ['weather'] [0] [description] NameError: имя 'description' не определено

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
}

1 Ответ

0 голосов
/ 26 января 2020

Проблема windspeed=data['wind'][0]['speed'], где вы просите Python получить доступ к 0-му индексу списка wind, которого на самом деле не существует (wind - словарь).

import json

content = """{
  "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
}"""

data = json.loads(content)
print(f'Temp is {data["main"]["temp"]}, and wind speed is {data["wind"]["speed"]}.')

Выходы:

Temp is 280.32, and wind speed is 4.1.
...