如何在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
相关产品推荐
相关产品推荐

