python - Python解析和遍历json数据
问题描述
#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"
}
解决方案
该weather
键包含一个字典列表,因此[0]
如果您想要列表第一个条目的描述,您应该使用:
future_description_day_0 = json_data['list'][0]['weather'][0]['description']
future_description_day_1 = json_data['list'][1]['weather'][0]['description']
推荐阅读
- oop - 在 Kotlin 的超类构造函数中使用抽象值
- flutter - Flutter中DecorationImage()的onError方法
- python - 如何从加载缓慢的网站中抓取表格数据
- python - 如何检索 python-ldap 可用的每个 objectClass?
- ruby-on-rails - rails many_to_many 关联问题
- c++ - 使用 CMake 使用 Network 构建 Qt 项目会导致未定义的引用
- excel - Powerquery命令转换日期格式
- java - 如何使用 Java 反射创建 @Autowired 类的实例
- java - 如何通过 JInput 库将操纵杆单击打印到控制台?
- javascript - Vue 和 Vuex:更改状态时不调用计算属性