Draft 7版本JSON Schema嵌套对象依赖documentType的必填校验不生效
错误原因
你的Schema未生效核心是两处语法和逻辑问题:
- 语法错误:将
references的required校验规则错误写在了根对象的properties节点下,required是对象级校验关键字,必须和properties平级、归属于对应要校验的对象schema内部,不会在properties的子配置中生效 - 逻辑缺失:根节点的全局必填列表未包含
general、references,这两个核心字段缺失时不会触发后续条件校验,同时原oneOf分支的匹配规则不够明确,容易出现分支穿透
修正后完整Schema
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": [ "apiVersion", "apiDate", "general", "references" ], "properties": { "apiVersion": { "type": "string", "description": "The version of the json file" }, "apiDate": { "type": "string", "description": "The date when the json version was published" }, "general": { "$ref": "#/definitions/general_identifiers" }, "references": { "type": "object", "properties": { "invoiceId": { "type": "string" }, "invoiceDate": { "type": "string" }, "creditNoteId": { "type": "string" }, "creditNoteDate": { "type": "string" } } } }, "allOf": [ { "if": { "properties": { "general": { "properties": { "documentType": { "const": "invoice" } }, "required": ["documentType"] } } }, "then": { "properties": { "references": { "required": ["invoiceId", "invoiceDate"] } } } }, { "if": { "properties": { "general": { "properties": { "documentType": { "const": "creditNote" } }, "required": ["documentType"] } } }, "then": { "properties": { "references": { "required": ["creditNoteId", "creditNoteDate"] } } } } ], "definitions": { "general_identifiers": { "type": "object", "required": [ "documentType" ], "properties": { "documentType": { "enum": [ "invoice", "creditNote" ] } } } } }
改动说明
- 改用
allOf包裹两组if/then/else条件分支,比原oneOf逻辑更清晰,完全兼容draft-07规范 - 根节点必填列表新增
general、references,避免核心字段缺失时校验失效 - 条件分支的必填规则直接作用于
references对象层级,确保校验逻辑正确触发
内容的提问来源于stack exchange,提问作者bugCreator
相关产品推荐
相关产品推荐

