按照示例,我能够引用在另一个 JSON 模式中声明的特定属性,并且一切都按预期进行,但是我还没有找到一种方法来扩展基本 JSON 模式与另一个基本模式的定义,而无需显式引用每一个属性。
似乎这将是有用的,但我还没有发现迹象表明它可能与否。
想象一下基本模式things
:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://example.com/thing.json",
"type": "object",
"additionalProperties": false,
"properties": {
"url": {
"id": "url",
"type": "string",
"format": "uri"
},
"name": {
"id": "name",
"type": "string"
}
},
"required": ["name"]
}
如果我想要一个更具体的person
模式来重用thing
我可以做的两个属性:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://example.com/thing/person.json",
"type": "object",
"additionalProperties": false,
"properties": {
"url": {
"$ref": "http://example.com/thing.json#/properties/url",
},
"name": {
"$ref": "http://example.com/thing.json#/properties/name",
},
"gender": {
"id": "gender",
"type": "string",
"enum": ["F", "M"]
},
"nationality": {
"id": "nationality",
"type": "string"
},
"birthDate": {
"id": "birthDate",
"type": "string",
"format": "date-time"
}
},
"required": ["gender"]
}
但是,我发现这种方法存在两个问题:
- 一旦更新了超定义,依赖的模式也必须更新
- 手动维护所有这些引用变得繁琐/冗长
- 规则(如
required: name
)不是引用定义的一部分
有没有办法通过使用单个全局引用来获得以下有效的 JSON 模式?
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://example.com/thing/person.json",
"type": "object",
"additionalProperties": false,
"properties": {
"url": {
"id": "url",
"type": "string",
"format": "uri"
},
"name": {
"id": "name",
"type": "string"
}
"gender": {
"id": "gender",
"type": "string",
"enum": ["F", "M"]
},
"nationality": {
"id": "nationality",
"type": "string"
},
"birthDate": {
"id": "birthDate",
"type": "string",
"format": "date-time"
}
},
"required": ["name", "gender"]
}
我尝试$ref
在架构的根目录中包含,如下所示:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://jsonschema.net/thing/person",
"type": "object",
"additionalProperties": false,
"$ref": "http://example.com/thing.json",
"properties": {
"gender": {/* ... */},
"nationality": {/* ... */},
"birthDate": {/* ... */}
},
"required": ["gender"]
}
这具有继承thing
属性但忽略所有其他属性的效果:
gender: Additional property gender is not allowed
nationality: Additional property nationality is not allowed
birthDate: Additional property birthDate is not allowed