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

如何修改JSON Schema以限制depends_on数组仅包含根对象的键名(排除所属父键)

Solution to Restrict depends_on to Valid Root Keys (Excluding Parent Key)

To enforce that each depends_on array only contains existing root keys and excludes its parent key, we'll modify the schema using JSON Schema Draft 07+ features (specifically the $data keyword, which is widely supported in libraries like AJV).

Modified Schema

{
  "type": "object",
  "patternProperties": {
    "^.+$": {
      "type": "object",
      "properties": {
        "depends_on": {
          "type": "array",
          "items": {
            "type": "string",
            // Prevent the array from including the parent key
            "not": {
              "const": {"$data": "1"}
            },
            // Ensure each item is a valid key present at the root
            "allOf": [
              {
                "$data": "#",
                "required": [{"$data": "0"}]
              }
            ]
          }
        }
      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false
}

Key Changes Explained

  • Excluding the Parent Key: The not: {const: {"$data": "1"}} rule uses $data: "1" to reference the key of the parent object (the root-level key that owns this depends_on array). This ensures the array can't include its own parent key.
  • Validating Root Keys: The $data: "#" references the entire root JSON object. We then apply required: [{"$data": "0"}], where $data: "0" points to the current item in the depends_on array. This guarantees the root object has a key matching the item.
  • Preventing Extra Properties: The additionalProperties: false constraints (at both levels) ensure no unexpected properties are added to the objects under root keys or the depends_on container.

Fallback for Older JSON Schema Drafts

If your implementation doesn't support $data (common in older drafts), you can only enforce this with static keys using enum. This is less flexible but works for fixed root keys:

{
  "type": "object",
  "properties": {
    "foo": {"type": "object", "properties": {"depends_on": {"type": "array", "items": {"enum": []}}}},
    "bar": {"type": "object", "properties": {"depends_on": {"type": "array", "items": {"enum": ["foo"]}}}}
  },
  "required": ["foo", "bar"],
  "additionalProperties": false
}

内容的提问来源于stack exchange,提问作者Mohammad Reza Bozorgmehr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:52:46