如何基于父JSON Schema属性值校验子Schema同名属性取值一致性
错误点修正
你原来的写法有两个核心错误:
if/then是JSON Schema的顶级条件关键字,不需要嵌套在dependentSchemas下,dependentSchemas仅用于「指定属性存在时才触发对应校验」的场景,和你的需求不匹配- 原Schema存在语法问题:
order.id的类型定义错误,缺少type关键字包裹
正确的Schema实现
{ "type": "object", "properties": { "action": { "enum": ["get", "post"] }, "order": { "type": "object", "properties": { "id": { "type": "string" }, "action": { "enum": ["get", "post"] } }, "required": ["id", "action"] } }, "required": ["action", "order"], "if": { "properties": { "action": { "const": "get" } } }, "then": { "properties": { "order": { "properties": { "action": { "const": "get" } } } } }, "else": { "properties": { "order": { "properties": { "action": { "const": "post" } } } } } }
如果你后续会扩展action的枚举值,不想每次都新增条件分支,也可以用JSON Schema的$data关键字(需要确认你使用的jsonschema库支持该特性,主流库如Python的jsonschema、前端的Ajv都兼容),写法更简洁:
{ "type": "object", "properties": { "action": { "enum": ["get", "post"] }, "order": { "type": "object", "properties": { "id": { "type": "string" }, "action": { "const": { "$data": "/action" } } }, "required": ["id", "action"] } }, "required": ["action", "order"] }
校验效果验证
注:你提供的测试用例存在JSON语法错误,id属性定义后缺少逗号,校验前需要先修正。
- 修正后的正向用例可以正常通过校验
- 修正后的反向用例会触发
action取值不匹配的校验错误
内容的提问来源于stack exchange,提问作者Murtaza
相关产品推荐
相关产品推荐

