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

使用Python或pytest编写校验JSON字段数量与结构的单元测试

实现方案

完全可以通过Python + pytest实现该需求,你可以按以下步骤完成JSON结构校验:

步骤1:安装依赖

需要先安装pytest测试框架:
pip install pytest

步骤2:编写测试代码

你可以同时校验字段数量上限和字段结构匹配两个维度,以下是完整示例代码:

import json
import pytest

# 配置校验规则
MAX_ALLOWED_FIELD_COUNT = 9
# 可选:如果需要校验字段名是否正确,可预先定义合法字段集合
EXPECTED_FIELD_SET = {
    "name",
    "components",
    "url",
    "image",
    "Thresholdtime",
    "WaferYield",
    "datePublished",
    "downTime",
    "description"
}

def load_json(file_path: str) -> dict:
    with open(file_path, "r", encoding="utf-8") as f:
        return json.load(f)

# 传入所有需要校验的JSON文件路径
@pytest.mark.parametrize("target_json_path", [
    "./test1.json",
    "./test2.json"
])
def test_json_validity(target_json_path):
    json_content = load_json(target_json_path)
    # 核心校验:字段数不超过9
    current_field_count = len(json_content.keys())
    assert current_field_count <= MAX_ALLOWED_FIELD_COUNT, f"校验失败:字段数为{current_field_count},超过最大允许值9"
    # 可选校验:字段完全匹配要求,无多余也无缺失
    current_fields = set(json_content.keys())
    extra_fields = current_fields - EXPECTED_FIELD_SET
    missing_fields = EXPECTED_FIELD_SET - current_fields
    assert len(extra_fields) == 0, f"校验失败:存在未定义的额外字段 {extra_fields}"
    assert len(missing_fields) == 0, f"校验失败:缺失必填字段 {missing_fields}"

步骤3:执行测试

将测试代码保存为test_json_check.py后,在终端执行以下命令即可运行所有校验:
pytest test_json_check.py -v
如果有不符合要求的JSON文件,pytest会直接抛出错误并给出具体异常原因。

自定义调整说明

如果不需要校验字段名是否匹配,只需要限制字段数不超过9,删除可选校验部分的代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:42:00