Python解析和遍历json数据

时间:2018-10-15 02:22:06

标签: python json api

#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))

所以我正在使用openweathermap API。我希望能够拉出当天[温度] [天气描述]和明天[温度] [天气描述]。问题是,当我尝试引用[天气描述]时,它是从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"
      }

1 个答案:

答案 0 :(得分:0)

sns.catplot(x="sex", y="survived", hue="class", kind="point", data=titanic); 键包含一则字典列表,因此,如果要获取列表的第一项的描述,则应使用weather

[0]