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

如何在JSON Schema中复用基础属性至嵌套对象?

解决方案

你的问题在于直接在properties对象中使用$ref不符合JSON Schema规范——properties的键必须是字段名称,而非Schema关键字。要实现公共属性与专属字段的组合,可以通过allOf关键字将公共Schema与专属字段的Schema合并,同时注意JSON Schema中类型名称是小写的string(你之前写的String是错误的)。

修正后的完整Schema示例

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://example.com/product.schema.json",
    "title": "Product",
    "description": "A product in the catalog",
    "type": "object",
    "properties": {
        "attributeA": {
            "type": "string"
        },
        "attributeB": {
            "type": "string"
        },
        "attributeC": {
            "type": "string"
        },
        "attributeD": {
            "type": "string"
        },
        "innerObjA": {
            "allOf": [
                {"$ref": "#/$defs/common_inner"},
                {
                    "properties": {
                        "exclusiveFieldX": {
                            "type": "string"
                        }
                    }
                }
            ]
        },
        "innerObjB": {
            "allOf": [
                {"$ref": "#/$defs/common_inner"},
                {
                    "properties": {
                        "exclusiveFieldY": {
                            "type": "string"
                        }
                    }
                }
            ]
        }
    },
    "$defs": {
        "common_inner": {
            "type": "object",
            "properties": {
                "attributeA": {"type": "string"},
                "attributeB": {"type": "string"},
                "attributeC": {"type": "string"}
            }
        }
    }
}

关键说明

  • allOf的作用:通过allOf数组将公共内部对象Schema(#/$defs/common_inner)与专属字段的Schema合并,确保innerObjA和innerObjB既包含公共属性,又各自拥有专属字段。
  • 类型名称修正:JSON Schema中所有类型名称均为小写(如string、number),你之前使用的String会导致验证失败。
  • 可选扩展:如果需要限制对象只能包含指定字段,可以在公共内部Schema或专属字段Schema中添加"additionalProperties": false,避免出现未定义的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:37:08