如何编写JSON Schema条件校验数组中mobile类型对象的endDate规则
问题原因
你之前编写的Schema不符合预期,是因为你把针对mobile类型的校验规则放在了items配置下,相当于强制要求所有type为mobile的数组元素的endDate都必须为空字符串,和需求中「至少有1个符合要求的mobile对象即可,其余mobile对象不受限制」的规则冲突。
符合要求的JSON Schema
{ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "properties": { "contacts": { "type": "array", "minItems": 1, "contains": { "type": "object", "properties": { "type": { "const": "mobile" }, "endDate": { "anyOf": [ { "type": "null" }, { "type": "string", "maxLength": 0 } ] } }, "required": ["type", "endDate"] }, "items": { "type": "object", "properties": { "type": { "type": "string" }, "endDate": { "type": ["string", "null"] }, "number": { "type": "string" } }, "required": ["type", "endDate", "number"] } } }, "required": ["contacts"] }
校验逻辑说明
- 核心规则通过
contains关键字实现:要求contacts数组中至少存在一个元素满足「type为mobile,且endDate为null或空字符串」,完全匹配你的业务要求 - 外层
items仅做基础字段类型校验,不会限制其他mobile类型对象的endDate取值,也不会对非mobile类型对象做额外规则校验 - 已补充必要的
required配置避免字段缺失导致的校验误判,你可以根据实际业务需求调整必填字段列表。
内容的提问来源于stack exchange,提问作者Rajesh Narravula
相关产品推荐
相关产品推荐

