JSON Schema if条件未满足仍触发校验规则的问题求解
JSON Schema校验规则异常问题解答
错误原因
你的if/then/else逻辑的作用域配置错误:
- 你将条件判断写在了
default属性的Schema定义内,此时if语句的校验对象是default属性对应的取值本身,而非default所属的上层元素对象 - 你在
if中写的properties.type.const=menu规则,实际是在判断「default的值本身有没有一个叫type的属性且值为menu」,而非判断上层元素对象的type字段值 - 当
default取值为布尔值、数字等非对象类型时,JSON Schema的properties关键字会直接判定校验通过,所以你的if分支始终被判定为真,触发了then里的整数/固定字符串限制,才会对布尔类型的default抛出类型错误
修正后的Schema
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "array", "title": "HubSpot Module", "items": { "type": "object", "properties": { "type": { "type": "string", "description": "字段类型" }, "default": { "type": ["string", "integer", "array", "boolean", "null", "number", "object"], "description": "字段默认值" } }, "required": [ "name", "label", "type" ], "if": { "properties": { "type": { "const": "menu" } } }, "then": { "properties": { "default": { "anyOf": [ { "type": "integer" }, { "type": "string", "const": "default" } ], "description": "菜单ID,取值为null时默认使用导航下的默认菜单", "default": null } } } } }
补充说明
修正后if/then/else的作用域是数组元素的完整对象,可正确读取同级的type属性做判断:
- 当
type为menu时,会额外限制default只能是整数或字符串"default" - 其他
type取值场景下,default保持原有的任意类型规则,不会触发额外限制
内容的提问来源于stack exchange,提问作者Erik B
相关产品推荐
相关产品推荐

