如何在Postman中实现JSON Schema的严格校验?
问题
我在Postman中进行JSON Schema校验,代码如下:
schema = { "items": { "required": [ "id", "payment_id", "bank_info_id", "account_number", "account_owner", "entity_sub_systems", "is_main", "public_id" ] } } pm.test("JSON schema check", function () { pm.response.to.have.jsonSchema(schema); });
该校验可检测必填键缺失或键名错误(如响应中用"isMain"替代"is_main"时会失败),但无法检测响应JSON中存在Schema未定义的额外键。例如:
schema = { "items": { "required": [ "id", "payment_id", "bank_info_id", "is_main", "public_id" ] } }
响应体:
{ "id":"65161", "payment_id":"65161", "bank_info_id":"65161", "is_main":true, "public_id":"65161", "something":"65161" }
此时校验不会失败。我尝试了Postman文档提到的Tiny validator(tv4),但Postman 10版本后不再支持,且该方法同样无法检测额外键:
var jsonData = JSON.parse(responseBody); pm.test('Checking Response Against Schema Validation', function() { var result=tv4.validateMultiple(jsonData, schema); console.log(result); pm.expect(result.valid).to.be.true; });
请问如何实现响应JSON严格遵循指定JSON Schema键的校验?
解决方案
要实现严格校验,禁止响应中出现Schema未定义的额外键,只需在JSON Schema中添加additionalProperties: false配置,同时建议明确指定每个字段的类型,让校验逻辑更严谨。
1. 针对数组类型的响应(对应代码中的items结构)
如果响应是数组,每个数组元素为对象,需在items内部配置additionalProperties: false,可补充字段类型定义:
schema = { "type": "array", "items": { "type": "object", "required": [ "id", "payment_id", "bank_info_id", "account_number", "account_owner", "entity_sub_systems", "is_main", "public_id" ], "additionalProperties": false, // 禁止额外字段 "properties": { // 明确字段类型,增强校验精度 "id": {"type": "string"}, "payment_id": {"type": "string"}, "bank_info_id": {"type": "string"}, "account_number": {"type": "string"}, "account_owner": {"type": "string"}, "entity_sub_systems": {"type": "array"}, // 根据实际业务类型调整 "is_main": {"type": "boolean"}, "public_id": {"type": "string"} } } } pm.test("JSON schema check (strict mode)", function () { pm.response.to.have.jsonSchema(schema); });
2. 针对单个对象类型的响应
如果响应是单个对象(而非数组),直接在对象层级添加additionalProperties: false:
schema = { "type": "object", "required": [ "id", "payment_id", "bank_info_id", "is_main", "public_id" ], "additionalProperties": false, "properties": { "id": {"type": "string"}, "payment_id": {"type": "string"}, "bank_info_id": {"type": "string"}, "is_main": {"type": "boolean"}, "public_id": {"type": "string"} } } pm.test("JSON schema check (strict mode)", function () { pm.response.to.have.jsonSchema(schema); });
原理说明
additionalProperties: false是JSON Schema的标准关键字,用于限制对象只能包含Schema中properties定义的字段,或required列表中指定的字段(未定义properties时)。- Postman内置的JSON Schema校验器完全支持该关键字,无需依赖第三方工具,适配Postman 10及以上版本。
内容的提问来源于stack exchange,提问作者Igor Martakov
相关产品推荐
相关产品推荐

