Python解析和迭代json d

2024-04-20 01:14:24 发布

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

#current forecast
current_api = 'api.openweathermap.org/data/2.5/weather?zip='
current_url_zip = current_api + urllib.parse.urlencode({'Zip': zip})
#current_url_key = 

json_data = requests.get(future_url_key).json()

#print (json_data)
future_temp_day_0 = json_data['list'][0]['main']['temp'] #current day
future_temp_day_1 = json_data['list'][1]['main']['temp'] #tomorrow
future_description_day_0 = json_data['list'][0]['weather']['description'] #current description
future_description_day_1 = json_data['list'][1]['weather']['description'] #current description
#Kelvin to F conversion
fTemp_0 = int((future_temp_day_0 - 273.15) * (9/5) + (32))
fTemp_1 = int((future_temp_day_1 - 273.15) * (9/5) + (32))

所以我使用的是OpenWeatherMapAPI。我想能够拉今天[温度][天气描述]和明天[温度][天气描述]。问题是当我尝试引用[weather description]时,它从json_data['list'][3]而不是json_data['list'][1]中提取它。它迭代到下一个点,即使我引用的是[1]项。你知道吗

{  
   "cod":"200",
   "message":0.0122,
   "cnt":40,
   "list":[  
      {  
         "dt":1519074000,
         "main":{  
            "temp":283.99,
            "temp_min":281.801,
            "temp_max":283.99,
            "pressure":989.94,
            "sea_level":1029.29,
            "grnd_level":989.94,
            "humidity":52,
            "temp_kf":2.19
         },
         "weather":[  
            {  
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{  
            "all":20
         },
         "wind":{  
            "speed":3.36,
            "deg":325.001
         },
         "rain":{
         },
         "sys":{  
            "pod":"d"
         },
         "dt_txt":"2018-02-19 21:00:00"
      },
      {  
         "dt":1519084800,
         "main":{  
            "temp":282.64,
            "temp_min":281.177,
            "temp_max":282.64,
            "pressure":990.6,
            "sea_level":1029.94,
            "grnd_level":990.6,
            "humidity":47,
            "temp_kf":1.46
         },
         "weather":[  
            {  
               "id":802,
               "main":"Clouds",
               "description":"scattered clouds",
               "icon":"03n"
            }
         ],
         "clouds":{  
            "all":36
         },
         "wind":{  
            "speed":3.17,
            "deg":319.502
         },
         "rain":{
         },
         "sys":{  
            "pod":"n"
         },
         "dt_txt":"2018-02-20 00:00:00"
      }

Tags: apijsondatamaindtfuturedescriptioncurrent
1条回答
网友
1楼 · 发布于 2024-04-20 01:14:24

weather键包含一个dict列表,因此如果需要列表第一个条目的描述,应该使用[0]

future_description_day_0 = json_data['list'][0]['weather'][0]['description']
future_description_day_1 = json_data['list'][1]['weather'][0]['description']

相关问题 更多 >