Python从WeatherAPI的JSON中提取多个headline字段问题求助
提取WeatherAPI警报中的多个headline字段
假设你已经通过接口请求拿到了解析后的JSON数据(存在response_json变量中),可以通过遍历数组的方式提取所有headline字段,代码示例如下:
# 检查alerts字段是否存在且alert数组非空,避免报错 if 'alerts' in response_json and response_json['alerts']['alert']: # 用列表推导式遍历alert数组,提取每个元素的headline alert_headlines = [alert['headline'] for alert in response_json['alerts']['alert']] else: # 无警报时返回空列表 alert_headlines = []
完整使用示例
结合你已有的字段提取逻辑,完整代码可以写成这样:
import requests # 替换为你的接口请求URL(已隐去密钥) url = "https://api.weatherapi.com/v1/forecast.json?key=YOUR_KEY&q=目标城市&alerts=yes" response = requests.get(url) response_json = response.json() # 提取已有字段 location = response_json['location']['name'] temp_c = response_json['current']['temp_c'] # 提取所有警报headline if 'alerts' in response_json and response_json['alerts']['alert']: alert_headlines = [alert['headline'] for alert in response_json['alerts']['alert']] else: alert_headlines = [] # 示例输出 print(f"位置: {location}") print(f"当前温度: {temp_c}°C") print("警报标题列表:") for num, headline in enumerate(alert_headlines, 1): print(f"{num}. {headline}")
针对JSON结构的说明
你的JSON片段中alerts.alert是数组结构,示例如下:
{
"alerts": {
"alert": [
{"headline": "高温预警", ...},
{"headline": "大风预警", ...}
]
}
}
因为这是一个数组,无法直接通过response_json['alerts']['alert']['headline']提取,必须遍历数组中的每个对象,逐个取出headline并存储到列表中,alert_headlines变量就是最终存储所有标题的列表,你可以根据需求进一步处理这个列表(比如拼接成字符串、存入数据库等)。
内容的提问来源于stack exchange,提问作者Catscanner
相关产品推荐
相关产品推荐

