JSON 与数据处理指南

JSON Schema 条件规则:按模式要求相关字段

使用 if/then 与 dependentRequired,避免选择字段缺失时意外触发条件分支。

Nav Tools ·

在 if 中要求选择字段存在

properties 在属性缺失时可能通过,条件只对明确选择值生效时,应在 if 内同时添加 required。

下面只在 mode 为 file 时要求 path,空对象不会触发该条件。

{"type":"object","if":{"properties":{"mode":{"const":"file"}},"required":["mode"]},
 "then":{"required":["path"]},"properties":{"path":{"type":"string","minLength":1}}}

分别测试三个状态

分别测试无 mode、file 模式缺 path、file 模式有非空 path,预期是通过、失败、通过。

如果 mode 全局必填,应另加外层 required;条件触发与全局完整性属于两个决定。

字段存在关系用依赖规则

dependentRequired 表示某字段出现时要求其他字段,不检查值,也不会自动形成双向依赖。

任意一个出现就要求另一个时需写两方向;要求取决于字段值时则使用 if/then。

{"dependentRequired":{"start":["end"],"end":["start"]}}
Neither field is globally required.

结构通过后继续验证语义

依赖可以要求 start 与 end 同时存在,但不会自动证明 end 晚于 start,Schema 只覆盖部分规则。

跨字段业务语义由应用继续验证,样例应分别覆盖结构错误与语义错误。

参考资料

← JSON 与数据处理指南