You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON Schema配置可选prepaid属性关联其他字段校验规则问题

问题原因

你当前的Schema存在两个核心问题:

  1. 原if子句仅限制了prepaid值为true的情况,但没有显式要求prepaid字段必须存在。JSON Schema的properties约束仅对已存在的字段生效,当prepaid字段缺失时,原if条件会被判定为成立,导致then块的必填规则被错误触发。
  2. 缺少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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:54:07