如何使用JSON Schema根据my_type值要求对应子属性必须存在?
JSON Schema嵌套属性依赖校验解决方案
你需要利用JSON Schema的if/then条件关键字,结合嵌套的属性约束来实现需求。以下是修改后的完整Schema:
{ "type": "object", "properties": { "my_type": { "type": "string" }, "t1_data": { "type": "object", "properties": { "id": { "type": "string" } } }, "t2_data": { "type": "object", "properties": { "id": { "type": "string" } } } }, "allOf": [ { "if": { "properties": { "my_type": { "const": "type1" } }, "required": ["my_type"] }, "then": { "properties": { "t1_data": { "required": ["id"] } }, "required": ["t1_data"] } }, { "if": { "properties": { "my_type": { "const": "type2" } }, "required": ["my_type"] }, "then": { "properties": { "t2_data": { "required": ["id"] } }, "required": ["t2_data"] } } ] }
规则说明
- 当
my_type等于"type1"时:if条件匹配,then块会强制要求t1_data必须存在,且t1_data的id属性为必填项 - 当
my_type等于"type2"时:第二个if条件匹配,then块强制要求t2_data必须存在,且t2_data的id属性为必填项 - 当
my_type为其他值或未提供时:两个if条件都不触发,无额外校验约束,直接通过校验
内容的提问来源于stack exchange,提问作者jonathangersam
相关产品推荐
相关产品推荐

