如何在Postman中验证含动态属性的API响应Schema
解决动态网站数量的API响应Schema验证问题
你的问题出在当前Schema只允许Websites对象包含storeone这一个属性,且默认拒绝任何额外属性。当API返回更多网站(比如storetwo)时,验证自然会失败。
要处理这种动态键的场景,你需要使用JSON Schema的additionalProperties关键字,定义所有未在properties中明确列出的属性必须遵循的结构,同时保留storeone作为必填项。
修改后的Schema如下:
var schema = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "Data": { "type": "array", "items": { "type": "object", "properties": { "CustomerName": { "type": "string" }, "Websites": { "type": "object", // 明确指定必填的storeone属性结构 "properties": { "storeone": { "type": "object", "properties": { "Keyone": { "type": "string" }, "Keytwo": { "type": "string" } }, "required": ["Keyone", "Keytwo"] } }, "required": ["storeone"], // 定义所有额外网站属性的统一结构 "additionalProperties": { "type": "object", "properties": { "Keyone": { "type": "string" }, "Keytwo": { "type": "string" } }, "required": ["Keyone", "Keytwo"] } } }, "required": ["CustomerName", "Websites"] } } }, "required": ["Data"] }
关键修改说明:
- 将
items后的数组包裹改为对象(原items: [{}]会限定数组仅能有一个元素,改为items: {}允许数组包含任意多个符合结构的元素,适配更灵活的返回场景) - 给
Websites添加additionalProperties,指定任何额外网站键(如storetwo、storethree)都必须包含Keyone和Keytwo两个必填字符串字段 - 保留
storeone的必填要求,确保该网站始终存在
修改后,不管API返回多少个网站,只要每个网站的结构符合Keyone和Keytwo的要求,且storeone存在,验证就能通过。
测试代码可直接沿用,无需修改:
var json = pm.response.json() pm.test('schema is valid', function(){ pm.expect(tv4.validate(json, schema)).to.be.true; })
内容的提问来源于stack exchange,提问作者Janith De Silva
相关产品推荐
相关产品推荐

