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

基于另一字段设置字段最小值的JSON Schema技术问询

如何在JSON Schema中让一个字段的最小值依赖另一个字段的值

需求很明确:当存在quotedAmountLower和quotedAmountUpper两个字段时,quotedAmountUpper的值必须严格大于quotedAmountLower的值。比如quotedAmountLower设为50,quotedAmountUpper就必须大于50。

你当前的JSON Schema代码如下:

{
  "properties": {
    "quotedAmountLower": {
      "type": "integer",
      "minimum": 0
    },
    "quotedAmountUpper": {
      "type": "integer",
      // more than quotedAmountLower
      "minimum": 0
    }
  }
}

解决方案1:使用$data关键字(推荐,灵活高效)

JSON Schema draft-06及以上版本支持$data关键字,可以直接引用实例中其他字段的值来设置验证规则。用它实现需求的代码如下:

{
  "properties": {
    "quotedAmountLower": {
      "type": "integer",
      "minimum": 0
    },
    "quotedAmountUpper": {
      "type": "integer",
      "exclusiveMinimum": { "$data": "1/quotedAmountLower" }
    }
  }
}
  • exclusiveMinimum确保quotedAmountUpper严格大于目标值
  • "$data": "1/quotedAmountLower"表示引用同级的quotedAmountLower字段的值,1/代表当前层级的父级(这里就是和quotedAmountUpper同级的位置)

解决方案2:使用if/then兼容旧版本(不推荐,不够灵活)

如果你的环境不支持$data,可以用if/then结构来实现,但这种方式需要枚举可能的quotedAmountLower值,扩展性差:

{
  "properties": {
    "quotedAmountLower": {
      "type": "integer",
      "minimum": 0
    },
    "quotedAmountUpper": {
      "type": "integer"
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "quotedAmountLower": { "const": 50 }
        },
        "required": ["quotedAmountLower"]
      },
      "then": {
        "properties": {
          "quotedAmountUpper": { "exclusiveMinimum": 50 }
        }
      }
    }
    // 如需支持其他值,需添加更多对应的if/then块
  ]
}

注意:主流JSON Schema验证库(如Ajv)都支持$data关键字,优先推荐第一种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:33:21