关于JSON Schema验证的困惑:为何不符合预期的JSON通过校验?
问题根源分析与解决方案
你的JSON能通过校验,核心是两个JSON Schema基础规则的遗漏:
1. requests对象未启用额外属性拦截
你仅在数组项的嵌套对象中设置了additionalProperties: false,但**requests本身没有添加该约束**。JSON里的Interface1字段和Schema中requests.properties定义的interfacename字段名不匹配,但由于additionalProperties默认值为true,requests会允许未定义的属性存在,导致Interface1直接通过校验,嵌套的数组项规则根本不会被触发。
2. 数组项校验规则从未生效
因为requests内的Interface1和Schema里的字段名interfacename不匹配,Schema不会对Interface1的内容应用任何校验逻辑——你写的required和additionalProperties: false规则完全没起作用,自然拦不住text这个额外属性。
修正后的Schema(静态匹配Interface1)
将requests.properties中的字段名改为和JSON一致的Interface1,同时给requests添加additionalProperties: false,禁止未定义属性:
{ "type": "object", "properties": { "requests": { "type": "object", "properties": { "Interface1": { "type": "array", "items": { "type": "object", "properties": { "foo": { "type": "string" }, "id": { "type": "number" } }, "required": [ "foo", "id" ], "additionalProperties": false } } }, "required": [ "Interface1" ], "additionalProperties": false } } }
动态接口名场景(可选)
如果接口名是Interface1、Interface2这类动态格式,可使用patternProperties匹配规则,同时限制requests仅允许该格式的属性:
{ "type": "object", "properties": { "requests": { "type": "object", "patternProperties": { "^Interface\\d+$": { "type": "array", "items": { "type": "object", "properties": { "foo": { "type": "string" }, "id": { "type": "number" } }, "required": [ "foo", "id" ], "additionalProperties": false } } }, "additionalProperties": false, "required": [ "Interface1" ] } } }
内容的提问来源于stack exchange,提问作者Mad Max
相关产品推荐
相关产品推荐

