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

如何在JSON Schema 2019-09中实现基于枚举值的条件必填验证

如何在JSON Schema 2019-09中实现基于枚举值的条件必填验证

嘿,这事儿用JSON Schema 2019-09里的if/then关键字就能完美解决!咱们的需求很明确:当type字段的值是Client时,font字段必须存在;如果是Corporate,font就可选。下面是具体的实现方案:

先看你给出的示例请求JSON:

{
  "type": "Client",
  "font": "Small",
  "occupation": "Super"
}

接下来是修改后的完整JSON Schema,完全满足你的条件验证需求:

{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "http://example.com/example.json",
    "title": "Root Schema",
    "type": "object",
    "default": {},
    "required": ["type", "occupation"],
    "properties": {
        "type": {
            "type": "string",
            "enum": ["Client", "Corporate"]
        },
        "font": {
            "type": "string"
        },
        "occupation": {
            "type": "string"
        }
    },
    "if": {
        "properties": {
            "type": {
                "const": "Client"
            }
        },
        "required": ["type"]
    },
    "then": {
        "required": ["font"]
    }
}

我来给你拆解下这个Schema的逻辑:

  • 基础要求:type和occupation是始终必填的,不管type的值是Client还是Corporate,这俩字段都得有。
  • if块:定义触发条件——当type字段存在且值严格等于Client时(用const精确匹配枚举值)。这里加required: ["type"]是为了避免在type字段缺失的情况下误触发条件判断。
  • then块:当if的条件满足时,强制执行这条规则——font字段必须存在。

测试一下就知道效果了:

  • 如果type是Client但没传font,验证直接失败;
  • 如果type是Corporate,不管有没有font,只要type和occupation都在,验证就能通过。

备注:内容来源于stack exchange,提问作者Hrithik Naha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 07:49:33