从JSON中提取特定值,但:TypeError:列表索引必须是整数而不是s

2024-04-18 04:58:06 发布

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

This is the JSON output from the API

{
"list":[
    {
          "dt": 1490791600,
          "temp": {
              "day": 58.26,
              "min": 39.65,
              "max": 67.37
          }
          "weather":  [
               {
                   "id": 500,
                   "main":  "Rain",
                   "description": "light rain",
                   "icon": "10d"
                }
     ]
     {
          "dt": 1480878000,
          "temp": {
              "day": 57.34,
              "min": 40.11,
              "max": 68.23
          }
          "weather":  [
               {
                   "id": 501,
                   "main":  "Showers",
                   "description": "possible rain",
                   "icon": "11d"
                }
     ]
  ]

}

This is my code. I want to try and pull the "id" for all of the weather dates.

json_obj = urllib2.urlopen(url)

data = json.load(json_obj)

for item in data['list']:

    temperature = item['temp']['min']
    forecast = item['weather']['main']

I am able to pull the temperature data without an issue but I get a TypeError: list indices must be integers not str when I try and pull the forecast data. I'm thinking this is due to list vs dictionary concepts. How can I pull the "id" values from this JSON data?


Tags: thetoidjsondataismainmin