【问题标题】:KeyError: 0 when trying to get data from JSONKeyError: 0 尝试从 JSON 获取数据时
【发布时间】: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


【解决方案1】:

问题是windspeed=data['wind'][0]['speed'],您要求 Python 访问 wind 列表的第 0 个索引,实际上该列表不存在(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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多