如何实现带嵌套对象与条件判断的JSON Schema必填属性逻辑?
嵌套条件下的JSON Schema必填字段验证问题
目标JSON结构
{ "stages": { "STAGE1": { "stage_type": "GSX", "params": { "x": "setting_x", // x为GSX类型阶段的必填项 "y": "setting_y" // y为GSX类型阶段的必填项 } }, "STAGE2": { "stage_type": "GSZ", "params": { "z": "setting_z" // z为GSZ类型阶段的必填项 } } } }
需求逻辑
- 当
stage_type为GSX时,params必须包含x和y字段 - 当
stage_type为GSZ时,params必须包含z字段
当前编写的Schema(存在问题)
{ "type": "object", "properties": { "stages": { "type": "object", "additionalProperties": { "type": "object", "properties": { "stage_type": { "type": "string", "enum": [ "GSX", "GSZ" ] }, "params": { "type": "object", "properties": { "x": { "type": "string" }, "y": { "type": "string" }, "z": { "type": "string" } }, "additionalProperties": false } }, "required": ["stage_type", "params"], "allOf": [ { "if": { "properties": { "stage_type": { "enum": ["GSX"] } } }, "then": { "required": ["x", "y"] } }, { "if": { "properties": { "stage_type": { "enum": ["GSZ"] } } }, "then": { "required": ["z"] } } ] }, "minProperties": 1, "uniqueItems": true } }, "additionalProperties": false }
问题分析
你当前的if-then规则错误地将x、y、z标记为外层对象的必填项,而实际上这些字段是嵌套在params对象中的,导致验证逻辑指向错误层级。
修正后的Schema
{ "type": "object", "properties": { "stages": { "type": "object", "additionalProperties": { "type": "object", "properties": { "stage_type": { "type": "string", "enum": ["GSX", "GSZ"] }, "params": { "type": "object", "properties": { "x": { "type": "string" }, "y": { "type": "string" }, "z": { "type": "string" } }, "additionalProperties": false } }, "required": ["stage_type", "params"], "allOf": [ { "if": { "properties": { "stage_type": { "const": "GSX" } }, "required": ["stage_type"] }, "then": { "properties": { "params": { "required": ["x", "y"] } } } }, { "if": { "properties": { "stage_type": { "const": "GSZ" } }, "required": ["stage_type"] }, "then": { "properties": { "params": { "required": ["z"] } } } } ] }, "minProperties": 1 } }, "additionalProperties": false }
关键修正点
- 调整规则作用层级:将
required规则嵌套在properties.params下,确保验证的是params对象内部的字段,而非外层对象。 - 强化条件严谨性:在
if中添加required: ["stage_type"],避免stage_type缺失时触发无效规则;单个枚举值用const替代enum,逻辑更清晰。 - 移除无效关键字:
uniqueItems是数组类型专属关键字,用于对象类型的stages字段无意义,已删除。
内容的提问来源于stack exchange,提问作者Róbert Lajos Bücs
相关产品推荐
相关产品推荐

