如何用Python检测JSON响应中weather字段内是否含‘rain’并输出1/0?
解决JSON响应中检测"rain"出现的问题
我猜你大概率是遇到了JSON解析失败、字段找不到或者大小写匹配的坑,别急,我给你一套靠谱的解决方案,直接就能用!
首先先上完整的可运行代码,涵盖了所有常见的边界情况:
import json def check_rain_in_weather(json_response): try: # 先处理JSON解析:如果输入是字符串就解析成字典,已经是字典就直接用 weather_data = json.loads(json_response) if isinstance(json_response, str) else json_response # 先检查weather字段是否存在,而且是列表(多数天气API返回的weather是数组形式) if "weather" not in weather_data or not isinstance(weather_data["weather"], list): return 0 # 遍历每一条天气数据 for weather_item in weather_data["weather"]: # 把main和description转成小写,避免大小写遗漏,同时用get()防止字段不存在报错 main_content = weather_item.get("main", "").lower() desc_content = weather_item.get("description", "").lower() # 只要任意一个字段包含rain子串就返回1 if "rain" in main_content or "rain" in desc_content: return 1 # 遍历完都没找到rain相关内容,返回0 return 0 except json.JSONDecodeError: print("Error: 输入的JSON格式有问题哦") return 0 except Exception as e: print(f"出了点小意外: {str(e)}") return 0 # 测试几个例子看看效果 test_case1 = '''{ "weather": [ {"main": "Rain", "description": "light rain shower"} ] }''' test_case2 = '''{ "weather": [ {"main": "Clouds", "description": "broken clouds"} ] }''' test_case3 = '''{ "weather": [ {"main": "Thunderstorm", "description": "heavy rain with thunder"} ] }''' print(check_rain_in_weather(test_case1)) # 输出1 print(check_rain_in_weather(test_case2)) # 输出0 print(check_rain_in_weather(test_case3)) # 输出1
几个关键细节给你拆解下:
- JSON解析容错:自动判断输入是字符串还是已解析的字典,同时捕获解析错误,避免程序直接崩溃。
- 字段安全访问:用
get()方法获取main和description,就算字段不存在也只会返回空字符串,不会抛出KeyError。 - 大小写不敏感匹配:把所有内容转成小写,不管是
Rain、RAIN还是heavy rain这种带rain的子串,都能精准检测到。
你之前可能踩的坑:
- 如果报
KeyError: 'weather':说明你的JSON里没有这个字段,代码里已经加了检查,直接返回0而不是报错。 - 如果报
JSONDecodeError:肯定是输入的JSON格式有问题,比如引号不配对、逗号多打了,代码里会提示你。 - 如果明明有rain却返回0:大概率是没做大小写转换,转成小写后就能解决这个问题。
把你的JSON响应传入这个函数,就能得到正确的1或0啦!
内容的提问来源于stack exchange,提问作者Glen
相关产品推荐
相关产品推荐

