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

JSON Schema IF条件中如何正确引用person定义内的age属性实现条件校验

问题原因

JSON Schema 中 properties 仅校验当前层级的字段,你在根层级的 if 块中写 person/age 会被识别为根下存在名为 person/age 的字段,自然无法匹配到嵌套在 child 下的 age 属性。

修正后的完整 Schema

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "definitions": {
        "person": {
            "type": "object",
            "properties": {
                "age": {
                    "type": "string"
                }
            }
        }
    },
    "properties": {
        "child": {
            "$ref": "#/definitions/person"
        }
    },
    "required": [
        "child"
    ],
    "if": {
        "properties": {
            "child": {
                "properties": {
                    "age": {
                        "const": "3"
                    }
                },
                "required": ["age"]
            }
        }
    },
    "then": {
        "properties": {
            "guardian": {
                "$ref": "#/definitions/person"
            }
        },
        "required": [
            "guardian"
        ]
    }
}

改动说明

  • 调整 if 块的属性层级:先声明匹配根下的 child 字段,再在 child 的Schema规则中声明匹配其下的age 字段值为 "3"
  • 新增 child 字段下的 required: ["age"] 规则,避免child未传age时误触发if校验逻辑

调整后测试数据 {"child":{"age":"3"}} 会命中if条件,触发then的guardian必填规则,校验失败,符合预期。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:06:00