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

Gaspar配置文件JSON Schema严格模式验证失败解决方案咨询

问题

我正尝试创建支持Gaspar的配置文件Schema,要求根对象必须至少指定Models和Controllers中的一个(或两者都有)。参考方案编写了简化版Schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "anyOf": [
        {
            "required": [
                "Models"
            ]
        },
        {
            "required": [
                "Controllers"
            ]
        }
    ],
    "properties": {
        "Models": {
            "type": "string"
        },
        "Controllers": {
            "type": "string"
        },
        "IgnoreAnnotations": {
          "type": "boolean"
        }
    }
}

该Schema在VS Code中验证正常,但使用完全严格模式验证时失败,报错:

################ Error message
>> compile              | schemas/json/gaspar.json (draft-07)(FullStrictMode)
>> Error: strict mode: required property "Models" is not defined at "https://json.schemastore.org/gaspar.json#/anyOf/0" (strictRequired)
##############################

尝试将properties移至anyOf内部,但引发了更多问题。请问如何让该Schema通过严格验证并正常工作?

解决方案

报错源于严格模式的strictRequired规则:当某个Schema节点声明了required数组,数组内的所有属性必须在该节点的properties(或patternProperties)中存在定义。你原来的anyOf子节点仅声明了required,但未在子节点内定义对应属性,因此触发校验错误。

无需移动根节点的properties,只需在anyOf的每个子节点中,通过$ref复用根节点的属性定义,同时保留required声明即可解决问题:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "Models": {
            "type": "string"
        },
        "Controllers": {
            "type": "string"
        },
        "IgnoreAnnotations": {
          "type": "boolean"
        }
    },
    "anyOf": [
        {
            "required": ["Models"],
            "properties": {
                "Models": { "$ref": "#/properties/Models" }
            }
        },
        {
            "required": ["Controllers"],
            "properties": {
                "Controllers": { "$ref": "#/properties/Controllers" }
            }
        }
    ]
}

关键说明

  • 根节点的properties保留所有属性的完整类型定义,确保配置文件的属性校验逻辑不受影响;
  • anyOf子节点通过$ref复用根节点的属性定义,既满足“至少包含Models或Controllers其一”的业务规则,又符合严格模式对required字段的校验要求;
  • 该写法兼容VS Code的正常验证逻辑,同时能通过严格模式校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:22:11