如何在Python中解析API返回的嵌套JSON并输出逐小时天气数据
问题
目标是将Open-Meteo API返回的JSON转为Python字典,遍历后每行输出小时时间和对应温度,共24行,期望格式:
2024-11-22T00:00 50.5 2024-11-22T01:00 49.8
现有代码遍历hourly字典时仅输出键名,尝试print(hour["time"])报错:
Traceback (most recent call last): File "/home/bthuy/briefing/weather.py", line 40, in <module> print(hour["time"]) ~~~~^^^^^^^^ TypeError: string indices must be integers, not 'str'
添加.values()后能输出各键对应的列表,但无法将time和temperature_2m的对应值配对输出。
解决方案
核心问题是对Python字典和列表的遍历逻辑理解偏差:
- 直接遍历字典
hourly时,循环变量拿到的是字典的键名(字符串类型),而非键对应的数据; - 遍历
hourly.values()时,拿到的是每个键对应的完整列表,无法直接获取同位置的时间和温度配对。
正确的做法是提取time和temperature_2m对应的两个列表,用zip()函数将两个列表的对应元素打包,再遍历输出:
import requests url = "https://api.open-meteo.com/v1/forecast" params = { "latitude": 37.897, "longitude": -91.129, "hourly": ["temperature_2m", "precipitation_probability", "precipitation", "weather_code"], "temperature_unit": "fahrenheit", "wind_speed_unit": "mph", "precipitation_unit": "inch", "forecast_days": 1 } response = requests.get(url, params) body_dict = response.json() # 提取时间与温度的列表 hourly_times = body_dict["hourly"]["time"] hourly_temps = body_dict["hourly"]["temperature_2m"] # 配对并输出对应数据 for time, temp in zip(hourly_times, hourly_temps): print(f"{time} {temp}")
代码说明
- 从API返回的字典中,直接提取
hourly下的time和temperature_2m两个列表,它们的元素位置一一对应; zip(hourly_times, hourly_temps)会将两个列表中索引相同的元素配对成元组,每次循环即可拿到一组时间和温度值;- 用f-string格式化输出,符合期望的格式要求。
内容的提问来源于stack exchange,提问作者bimmo
相关产品推荐
相关产品推荐

