JSON Schema配置可选prepaid属性关联其他字段校验规则问题
问题原因
你当前的Schema存在两个核心问题:
- 原
if子句仅限制了prepaid值为true的情况,但没有显式要求prepaid字段必须存在。JSON Schema的properties约束仅对已存在的字段生效,当prepaid字段缺失时,原if条件会被判定为成立,导致then块的必填规则被错误触发。 - 缺少
prepaid不存在/值为false时的禁显规则配置,且原Schema遗漏了monthlyRate字段的属性声明。
修正后的完整Schema
{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/object1638395656.json", "type": "array", "items": { "type": "object", "required": [ "id", "name" ], "properties": { "id": { "type": "string", "format": "uuid" }, "name": { "type": "string", "minLength": 1 }, "overageRate": { "type": "number", "minimum": 0 }, "pointsPerMonth": { "type": "number", "minimum": 0 }, "monthlyRate": { "type": "number", "minimum": 0 }, "prepaid": { "type": "boolean" } }, "if": { "required": ["prepaid"], "properties": { "prepaid": { "const": true } } }, "then": { "required": [ "pointsPerMonth", "monthlyRate", "overageRate" ] }, "else": { "properties": { "overageRate": false, "pointsPerMonth": false, "monthlyRate": false } } } }
修改点说明
- 给
if子句新增了"required": ["prepaid"]约束,确保只有当prepaid字段显式存在且值为true时,才会触发then块的必填校验,解决了字段缺失时误判的问题。 - 新增了
else子句,将三个number类型字段的schema设为false:只要prepaid不存在、或值为false时,这三个字段只要出现在JSON中就会触发校验失败,满足禁显需求。 - 补充了原来遗漏的
monthlyRate字段声明,避免字段未定义导致的校验逻辑异常。
内容的提问来源于stack exchange,提问作者Gargoyle
相关产品推荐
相关产品推荐

