JSON 如果可选属性无效,架构会抛出验证错误
JSON Schema throw validation error if invalid optional attribute
我有一个 json 架构,如下所示,它具有三个可选的属性高度、重量和体积。但我想在这里做以下额外检查:
- 如果传递除了高度、重量和体积之外的任何其他属性,则它应该抛出错误
不确定如何实现这一点,因为这些是可选属性。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
}
}
}
}
您要查找的是 additionalProperties
键。来自 JsonSchema docs
The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword. By default any additional properties are allowed.
所以,这会变成:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
},
"additionalProperties": false
}
}
}
据我了解,自 draft 00
起就支持此功能,因此 draft 4
应该没问题,但请注意,第 8 版已发布。
我有一个 json 架构,如下所示,它具有三个可选的属性高度、重量和体积。但我想在这里做以下额外检查:
- 如果传递除了高度、重量和体积之外的任何其他属性,则它应该抛出错误
不确定如何实现这一点,因为这些是可选属性。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
}
}
}
}
您要查找的是 additionalProperties
键。来自 JsonSchema docs
The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword. By default any additional properties are allowed.
所以,这会变成:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"options": {
"type": "object",
"properties": {
"height": {
"type": "number"
},
"weight": {
"type": "number"
},
"volume": {
"type": "number"
}
},
"additionalProperties": false
}
}
}
据我了解,自 draft 00
起就支持此功能,因此 draft 4
应该没问题,但请注意,第 8 版已发布。