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

如何在JSON Schema中用通配符键定义路径并实现条件验证?

可行,以下是实现方案

你可以通过JSON Schema的可复用定义($defs) + 条件判断(if/then) + 模式属性(patternProperties) 实现该需求,完全无需重复编写common/uncommon/rare的规则。

目标YAML示例

material: iron_leggings
displayName: "Plated Leggings"
rare:
  effects:
    entry0:
      slot: legs
      name: life_steal

对应的JSON Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "material": { "type": "string" },
    "displayName": { "type": "string" }
  },
  "patternProperties": {
    "^(common|uncommon|rare)$": {
      "$ref": "#/$defs/rarityEffects"
    }
  },
  "additionalProperties": false,
  "if": {
    "properties": {
      "material": { "pattern": ".*leggings.*" }
    },
    "required": ["material"]
  },
  "then": {
    "$defs": {
      "slotMustBeLegs": {
        "properties": {
          "slot": { "const": "legs" }
        },
        "required": ["slot"]
      }
    },
    "patternProperties": {
      "^(common|uncommon|rare)$": {
        "properties": {
          "effects": {
            "patternProperties": {
              ".*": { "$ref": "#/$defs/slotMustBeLegs" }
            },
            "additionalProperties": false
          }
        },
        "required": ["effects"]
      }
    }
  },
  "$defs": {
    "rarityEffects": {
      "type": "object",
      "properties": {
        "effects": {
          "type": "object",
          "patternProperties": {
            ".*": {
              "type": "object",
              "properties": {
                "slot": { "type": "string" },
                "name": { "type": "string" }
              },
              "required": ["slot", "name"]
            }
          },
          "additionalProperties": false
        }
      },
      "required": ["effects"]
    }
  }
}

核心逻辑说明

  1. 正则匹配稀有度字段:用^(common|uncommon|rare)$一次性匹配三个稀有度键,直接复用$defs.rarityEffects的基础结构,彻底避免重复编写规则。
  2. 条件触发验证:if块检测material是否包含"leggings"字符串,满足条件时才启用强制验证逻辑。
  3. 通配符匹配任意entry:用patternProperties: { ".*": ... }匹配effects下任意名称的entry(比如entry0、customEntry等),无需提前指定entry键名。
  4. 强制slot规则:条件满足时,所有匹配到的entry的slot字段必须为"legs",通过$ref复用规则避免重复代码。
  5. 字段合法性控制:additionalProperties: false确保对象中只能存在定义过的字段,避免多余字段干扰验证。

验证效果

  • 当material包含"leggings"时,只要common/uncommon/rare中任意一个的effects下有entry的slot不是"legs",验证直接失败。
  • 当material不包含"leggings"时,slot只需满足字符串类型要求即可,无强制值限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:15:49