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

如何在JSON Schema中根据operator值约束BooleanCondition的value类型?

基于operator字段的JSON Schema条件约束实现

当然可以实现,JSON Schema(Draft 07及以上版本)提供了原生的条件校验能力来处理这类场景,下面是两种常用的实现方案:

方案一:使用if/then/elseIf 条件分支

这种方式适合逐个定义操作符对应的规则,逻辑直观:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "operator": {
      "type": "string",
      "enum": ["in", "eq"] // 限定允许的操作符范围
    },
    "value": {} // 基础占位,由条件分支补充具体约束
  },
  "required": ["operator", "value"], // 确保必填字段存在
  
  // 匹配operator为'in'的情况
  "if": {
    "properties": {
      "operator": { "const": "in" }
    }
  },
  "then": {
    "properties": {
      "value": {
        "type": "array",
        "items": { "type": ["string", "integer"] }
      }
    }
  },
  
  // 匹配operator为'eq'的情况
  "elseIf": {
    "properties": {
      "operator": { "const": "eq" }
    }
  },
  "then": {
    "properties": {
      "value": {
        "type": ["string", "number", "boolean", "null"],
        "not": { "type": "array" } // 明确排除数组类型
      }
    }
  },
  
  // 兜底处理未定义的操作符
  "else": {
    "properties": {
      "operator": { "errorMessage": "Unsupported operator" }
    }
  }
}

说明:

  • const用于精准匹配operator的取值(Draft 07+支持,低版本可替换为enum: ["in"])
  • if匹配目标操作符后,then会强制value字段满足对应的类型约束
  • required确保operator和value两个字段必须存在
  • else分支可以用来处理未定义的操作符,返回明确的错误提示

方案二:使用oneOf 枚举所有操作符场景

如果操作符类型较多,这种方式更清晰,每个子Schema独立定义一种操作符的完整规则:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "oneOf": [
    // 定义'in'操作符的完整约束
    {
      "properties": {
        "operator": { "const": "in" },
        "value": {
          "type": "array",
          "items": { "type": ["string", "integer"] }
        }
      },
      "required": ["operator", "value"],
      "additionalProperties": false // 可选,禁止额外未知字段
    },
    // 定义'eq'操作符的完整约束
    {
      "properties": {
        "operator": { "const": "eq" },
        "value": {
          "type": ["string", "number", "boolean", "null"],
          "not": { "type": "array" }
        }
      },
      "required": ["operator", "value"],
      "additionalProperties": false
    }
  ]
}

说明:

  • oneOf确保JSON只能匹配其中一个子Schema,避免同时满足多个操作符规则的情况
  • 每个子Schema独立定义操作符和对应的value约束,逻辑隔离,便于维护
  • additionalProperties: false可以防止出现未定义的字段,增强校验严格性

版本兼容性

如果你的JSON Schema解析器仅支持Draft 06及以下版本,只需将const替换为enum: ["目标操作符"]即可,核心逻辑保持不变。

内容的提问来源于stack exchange,提问作者revy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:50:51