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

Postman中JSON数组的Schema验证问题咨询

在Postman中完成JSON数组的Schema验证配置

我来帮你补全完整的Schema验证代码,并且一步步说明怎么在Postman里配置测试:

首先,根据你提供的测试数据,我把Schema补全,同时兼顾所有字段的类型验证,包括允许null的字段:

pm.test("响应数据符合Schema规范", function () {
    var schema = {
        "type": "object",
        "required": ["staffId", "staffName", "staffEmail", "shopDetails"], // 可根据实际需求调整必填字段
        "properties": {
            "staffId": { "type": "integer" },
            "staffName": { "type": "string" },
            "staffEmail": { "type": "string", "format": "email" }, // 额外校验邮箱格式合法性
            "isAdmin": { "type": ["boolean", "null"] }, // 允许布尔值或null两种类型
            "isSuperAdmin": { "type": ["boolean", "null"] },
            "shopDetails": {
                "type": "array",
                "minItems": 1, // 确保数组至少包含一个店铺信息
                "items": {
                    "type": "object",
                    "required": ["shopId", "shopName", "shopAddress"], // 数组内对象的必填字段
                    "properties": {
                        "shopId": { "type": "integer" },
                        "shopName": { "type": "string" },
                        "shopAddress": { "type": "string" },
                        "shopLocality": { "type": "string" },
                        "shopCity": { "type": "string" },
                        "shopState": { "type": "string" },
                        "stateCode": { "type": "string" }
                    }
                }
            }
        }
    };
    // 用Postman内置的验证器执行Schema校验
    pm.response.to.have.jsonSchema(schema);
});

代码细节说明:

  • 必填字段控制:required数组用来指定响应中必须存在的核心字段,你可以根据业务需求随时增减;
  • 多类型兼容:对于isAdmin这类允许返回null的字段,用["boolean", "null"]定义,既支持布尔值也兼容空值;
  • 数组规则约束:shopDetails数组通过minItems:1避免空数组的情况,items里则明确了数组内每个店铺对象的完整字段规则;
  • 格式增强校验:给staffEmail加上format:"email",能自动验证邮箱格式是否符合规范。

Postman操作步骤:

  1. 打开需要测试的请求,切换到Tests标签页;
  2. 把上面的代码粘贴到编辑区;
  3. 发送请求后,查看底部的Test Results:如果响应数据完全符合Schema规则,测试会显示Pass;如果有不符合的地方,会明确提示错误原因(比如字段类型不匹配、缺少必填字段等)。

你可以根据实际业务场景调整Schema规则,比如修改字段类型、调整数组的最大/最小元素数、增减必填项等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:47:46