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

如何修改数据校验脚本以输出缺失的键及返回false的键?

我帮你调整了脚本,现在它能明确打印出缺失的键、类型验证失败的键,以及返回False响应的布尔类型键,同时还会定位到具体是哪条记录出了问题。修改后的代码如下:

def validate_record_schema():
    """验证记录中0个或多个Payload字典是否使用正确类型,同时输出缺失的键和验证失败的键"""
    err_path = "root"
    for record_idx, record in enumerate(original_data):
        try:
            device = record["Device"]
            # 定义需要验证的键与对应类型规则,可按需扩展
            validation_rules = {
                "ManualAdded": bool,
                "Location": (str, type(None)),
                "Version": (str, type(None)),
                "Vendor": (str, type(None)),
                "Language": list,
                "Fullname": (str, type(None)),
                "SchemaVersion": (str, type(None))
            }
            
            print(f"=== 验证第 {record_idx + 1} 条记录 ===")
            missing_keys = []
            invalid_type_keys = []
            false_response_keys = []  # 记录返回False的布尔类型键
            
            for key, expected_type in validation_rules.items():
                # 检查键是否存在
                if key not in device:
                    missing_keys.append(key)
                    continue
                
                value = device[key]
                # 验证值的类型(支持单个类型或多类型元组,比如允许字符串或None)
                if isinstance(expected_type, tuple):
                    if not isinstance(value, expected_type):
                        expected_types = ", ".join(t.__name__ for t in expected_type)
                        invalid_type_keys.append(f"{key}: 实际类型是 {type(value).__name__},期望类型为 {expected_types}")
                else:
                    if not isinstance(value, expected_type):
                        invalid_type_keys.append(f"{key}: 实际类型是 {type(value).__name__},期望类型为 {expected_type.__name__}")
                
                # 检查布尔类型键是否返回False响应
                if expected_type is bool and value is False:
                    false_response_keys.append(key)
            
            # 输出所有错误信息
            if missing_keys:
                print(f"❌ 缺失的键: {', '.join(missing_keys)}")
            if invalid_type_keys:
                print("❌ 类型验证失败的键:")
                for msg in invalid_type_keys:
                    print(f"  - {msg}")
            if false_response_keys:
                print(f"⚠️ 返回False响应的键: {', '.join(false_response_keys)}")
            
            # 无错误时提示验证通过
            if not missing_keys and not invalid_type_keys and not false_response_keys:
                print("✅ 该记录验证通过")
                
        except KeyError as e:
            print(f"❌ 第 {record_idx + 1} 条记录错误: 缺失顶级键 {e}")
        except Exception as e:
            print(f"❌ 第 {record_idx + 1} 条记录发生未知错误: {str(e)}")

主要修改点说明:

  • 用enumerate遍历记录,能精准定位到出问题的是哪一条记录,排查起来更方便;
  • 把原来的元组列表改成了字典validation_rules,结构更清晰,后续添加新的验证键也更直观;
  • 分三类收集问题:缺失的键、类型不匹配的键、返回False的布尔键,每种问题都有明确的提示;
  • 类型验证支持多类型(比如允许str或None),和你原来的逻辑保持一致;
  • 增加了异常捕获,如果记录里连Device这个顶级键都没有,也会给出明确提示;
  • 输出信息加了 emoji 标记,看起来更醒目,也可以根据你的喜好去掉。

只要确保你的数据源变量original_data已经正确定义,直接调用这个函数就能看到详细的验证结果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:42:13