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

如何用Python批量遍历vars目录JSON文件依次与config.json对比校验

问题根因

原脚本无法实现全量批量校验,核心问题有3处:

  • return_func_settings 函数接收的是待校验文件的完整列表,内部循环遍历文件时反复覆盖配置变量,循环结束后仅返回列表最后一个文件的内容,前面的文件全部被跳过
  • 两个校验逻辑函数仅全局调用一次,没有针对每个待校验文件单独执行校验流程
  • 原键匹配逻辑存在漏洞:只要遍历到的最后一个键匹配,就会判定全量匹配,前面出现的缺失键不会触发最终异常;同时打开文件后未做关闭处理,存在资源泄漏风险

注意:你提供的JSON示例存在语法错误,相邻键值对之间缺少逗号分隔,实际运行前请确保所有JSON文件语法合法,否则会触发JSON解析报错。

修复后完整可运行代码
import os
import json

VARS_PATH = './vars'
BENCHMARK_FILE = 'config.json'

def load_json_settings(file_path):
    """通用JSON配置加载工具,自动处理文件关闭"""
    with open(file_path, 'r', encoding='utf-8') as f:
        config_data = json.load(f)
    return {
        'file_name': os.path.basename(file_path),
        'settings': config_data['appSettings']
    }

def check_single_file(target_file_path, benchmark_config):
    """执行单个文件和基准配置的双维度校验"""
    target_config = load_json_settings(target_file_path)
    target_keys = set(target_config['settings'].keys())
    benchmark_keys = set(benchmark_config['settings'].keys())

    print(f"\n===== 校验 {target_config['file_name']} 对比 {benchmark_config['file_name']} =====")

    # 校验维度1:键总数比对
    if len(target_keys) != len(benchmark_keys):
        print(f"*警告*:键总数不一致,{target_config['file_name']} 含{len(target_keys)}个键,基准文件含{len(benchmark_keys)}个键")

    # 校验维度2:键名完全匹配校验
    missing_in_target = benchmark_keys - target_keys
    extra_in_target = target_keys - benchmark_keys

    if not missing_in_target and not extra_in_target:
        print(f"校验通过:{target_config['file_name']} 键名与基准文件完全一致")
        return True

    # 输出具体差异
    if missing_in_target:
        print(f"缺失键:{target_config['file_name']} 缺少基准键 {', '.join(missing_in_target)}")
    if extra_in_target:
        print(f"多余键:{target_config['file_name']} 存在基准文件未定义的键 {', '.join(extra_in_target)}")
    return False

def main():
    # 加载基准配置文件
    benchmark_path = os.path.join(VARS_PATH, BENCHMARK_FILE)
    if not os.path.exists(benchmark_path):
        raise FileNotFoundError(f"基准配置文件不存在:{benchmark_path}")
    benchmark_config = load_json_settings(benchmark_path)

    all_check_pass = True
    # 遍历目录逐个校验所有非基准的JSON文件
    for file_name in os.listdir(VARS_PATH):
        if not file_name.endswith('.json') or file_name == BENCHMARK_FILE:
            continue
        file_path = os.path.join(VARS_PATH, file_name)
        if not check_single_file(file_path, benchmark_config):
            all_check_pass = False

    # 输出全量校验结果
    print("\n===== 全量校验结束 =====")
    if all_check_pass:
        print("所有JSON文件键名校验通过")
    else:
        raise Exception("存在文件键名不匹配,请根据上述提示修正对应配置")

if __name__ == '__main__':
    main()
核心改动说明
  • 拆分通用单文件加载逻辑,用with上下文管理器自动处理文件关闭,避免资源泄漏
  • 遍历vars目录时,每识别到一个待校验JSON文件就单独触发一次校验流程,从根本上解决只校验最后一个文件的问题
  • 用集合差集计算键名差异,替换原有循环判断逻辑,避免“最后一个键匹配即全量通过”的逻辑漏洞
  • 区分“待校验文件缺失基准键”“待校验文件存在多余键”两种差异场景,报错提示更精准
  • 所有文件校验完成后再统一抛出最终异常,不会因为第一个文件出错就终止流程,导致后续文件无法校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:27:21