为所有属性指定必需属性的元架构
Metaschema specifying required attribute for all properties
我想自定义元架构,要求所有属性都具有附加属性,例如,我如何要求所有属性指定一个 "type"
?
那么这个架构应该会失败:
{
"$schema": "http://json-schema.org/schema#",
"title": "...",
"description": "...",
"type": "object",
"properties": {
"name": {
"description": "..."
}
}
}
但是这个应该会成功:
{
"$schema": "http://json-schema.org/schema#",
"title": "...",
"description": "...",
"type": "object",
"properties": {
"name": {
"description": "...",
"type": "string"
}
}
}
不幸的是,编写元模式并不容易。正在研究中,目前还没有很好的解决方案。
您必须复制要扩展的元架构,然后添加 "required": ["type"]
。
但是,既然我们在这里,也许我可以说服你不要这样做。在某些情况下,使 type
关键字成为必需会导致问题。这里有一些例子。 https://github.com/json-schema/json-schema/issues/172#issuecomment-124214534
编辑
进一步讨论后,我们发现这种特殊情况没有我们通常 运行 在扩展元模式时遇到的问题,因为它不需要递归。下面是扩展 draft-06 模式以包含名为 custom
的新关键字的示例,它是一个布尔值,仅在 properties
模式的顶层需要。
{
"allOf": [
{ "$ref": "http://json-schema.org/draft-06/schema#" },
{
"properties": {
"properties": {
"patternProperties": {
".*": {
"properties": {
"custom": { "type": "boolean" }
},
"required": ["custom"]
}
}
}
}
}
]
}
这是一个符合此元模式的示例模式。
{
"properties": {
"foo": {
"custom": true,
"not": { "type": "string" }
}
}
}
“foo”模式需要 custom
关键字,但 not
模式或顶级模式不需要。
我想自定义元架构,要求所有属性都具有附加属性,例如,我如何要求所有属性指定一个 "type"
?
那么这个架构应该会失败:
{
"$schema": "http://json-schema.org/schema#",
"title": "...",
"description": "...",
"type": "object",
"properties": {
"name": {
"description": "..."
}
}
}
但是这个应该会成功:
{
"$schema": "http://json-schema.org/schema#",
"title": "...",
"description": "...",
"type": "object",
"properties": {
"name": {
"description": "...",
"type": "string"
}
}
}
不幸的是,编写元模式并不容易。正在研究中,目前还没有很好的解决方案。
您必须复制要扩展的元架构,然后添加 "required": ["type"]
。
但是,既然我们在这里,也许我可以说服你不要这样做。在某些情况下,使 type
关键字成为必需会导致问题。这里有一些例子。 https://github.com/json-schema/json-schema/issues/172#issuecomment-124214534
编辑
进一步讨论后,我们发现这种特殊情况没有我们通常 运行 在扩展元模式时遇到的问题,因为它不需要递归。下面是扩展 draft-06 模式以包含名为 custom
的新关键字的示例,它是一个布尔值,仅在 properties
模式的顶层需要。
{
"allOf": [
{ "$ref": "http://json-schema.org/draft-06/schema#" },
{
"properties": {
"properties": {
"patternProperties": {
".*": {
"properties": {
"custom": { "type": "boolean" }
},
"required": ["custom"]
}
}
}
}
}
]
}
这是一个符合此元模式的示例模式。
{
"properties": {
"foo": {
"custom": true,
"not": { "type": "string" }
}
}
}
“foo”模式需要 custom
关键字,但 not
模式或顶级模式不需要。