You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python函数提取JSON中medium/high风险等级对应的alert-id列表

Python函数实现:筛选指定风险等级的告警ID

需求说明

  • 遍历JSON响应内容,匹配所有risk-level值为medium或high的条目
  • 匹配成功则将对应alert-id用.append()方法存入列表后返回
  • 无匹配结果时调用exit()退出程序

目前已实现单条件匹配返回逻辑,卡在如何传入带OR逻辑的列表进行匹配来获取独立结果的环节

参考JSON响应示例

[
    {'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},  
    {'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
    {'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
    {'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
]

实现代码

def filter_risk_alerts(response_data, target_risk_levels=["medium", "high"]):
    matched_alert_ids = []
    # 遍历所有响应条目
    for item in response_data:
        # OR逻辑匹配:当前风险等级在目标列表中即命中
        if item.get("risk-level") in target_risk_levels:
            matched_alert_ids.append(item.get("alert-id"))
    # 无匹配结果直接退出程序
    if not matched_alert_ids:
        exit()
    return matched_alert_ids

使用示例

if __name__ == "__main__":
    # 替换为实际获取的响应数据
    test_response = [
        {'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},  
        {'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
        {'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
        {'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
    ]
    result = filter_risk_alerts(test_response)
    print(result)
    # 输出示例:['6e310403-3db3-4b5f-cehd-16ffc648f7b7', '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf']

核心逻辑说明

  • 多条件OR匹配无需写冗余的并列判断,把所有要匹配的目标值存入列表后用in关键字判断即可,后续要调整匹配规则仅需修改target_risk_levels参数,不需要改动核心逻辑
  • 用.get()方法取字典值,避免键不存在时抛出异常
  • 最终返回的列表为所有命中规则的alert-id集合,无匹配时程序直接退出

内容的提问来源于stack exchange,提问作者NKDS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:45:04