为何JSON Schema Draft7的条件子模式校验规则无法正常生效?
问题原因及修复方案
核心错误点
- if关键字层级错误:你将
if逻辑写在address对象的properties字段下,会校验address内部的country属性,但你的country是和address平级的根属性,导致if条件永远无法匹配,类型校验规则不生效 - then/else结构不规范:直接在
then/else下写postal_code的规则是无效的,必须包裹在properties字段中才会被识别为属性校验规则 - Test-JSON特性限制:PowerShell的
Test-JSON命令不会自动处理Schema中的default字段,你没有在示例数据中显式传入country值,进一步导致逻辑分支永远不会触发 - 规则逻辑反向:你原有Schema的else分支定义加拿大场景下
postal_code类型为字符串,按这个规则示例2本就应该通过,如果你预期加拿大场景下该字段校验失败,需要调整else分支的类型规则
修正后的Schema示例
{ "type": "object", "properties": { "country": { "enum": [ "United States of America", "Canada" ] }, "address": { "type": "object", "properties": { "AddressLine1": { "type": "string" }, "postal_code": {} }, "required": [ "AddressLine1", "postal_code" ] } }, "required": ["country"], "if": { "properties": { "country": { "const": "United States of America" } } }, "then": { "properties": { "address": { "properties": { "postal_code": { "type": "integer" } } } } }, "else": { "properties": { "address": { "properties": { "postal_code": { "type": "integer" // 此处改为你需要的加拿大邮编校验规则即可实现示例2校验失败 } } } } } }
Test-JSON使用注意事项
- 需使用PowerShell 7.1及以上版本,旧版本不支持JSON Schema draft-07新增的
if/then/else关键字,会直接忽略相关规则 - 校验时需在数据中显式传入逻辑依赖的
country属性,不要依赖Schema的default字段自动填充
内容的提问来源于stack exchange,提问作者dakuji
相关产品推荐
相关产品推荐

