我使用JSON来验证YAML和JSON配置文件。在一个配置文件中,所有元素都是可选的。但只有有限的一组元素才被允许。
在下面给定的模式中,我需要更改什么,以便在JSON情况下空文件/文档也是有效的?
{
"$id": "https://snafu.com/api/service/publishing-mechanism/config-delta/1.0.0",
"$schema": "https://json-schema.org/draft/2019-09/schema",
"description": "....",
"type": "object",
"additionalProperties": false,
"properties": {
"plans": {
"type": "object",
"additionalProperties": false,
"minProperties": 1,
"patternProperties": {
"^.*$": {
"type": "object",
"additionalProperties": false,
"properties": {
"description": {
"type": "string"
},
"validation": {
"type": "string",
"enum": ["auto", "manual"]
},
"security": {
"type": "string",
"enum": ["api_key"]
}
}
}
}
}
}
}
发布于 2022-08-06 15:29:42
因此,在相当长的一段时间后,这里是解决方案,正在为我的项目的生产。
{
"$id": "https://snafu.com/api/service/publishing-mechanism/config-delta/1.0.0",
"$schema": "https://json-schema.org/draft/2019-09/schema",
"description": "....",
"$defs": {
"empty": {"type": "null"}
},
"type": "object",
"additionalProperties": false,
"properties": {
"plans": {
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"patternProperties": {
"^.+$": {
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"properties": {
"description": {
"minLength": 1,
"type": "string"
},
"security": {
"enum": ["api_key"],
"type": "string"
}
}
},
{ "$ref": "#/$defs/empty" }
]
}
}
},
{ "$ref": "#/$defs/empty" }
]
}
}
}
在这里,我使用oneOf
来拥有两个相互排斥的子模式。其中一个是所有可能的属性,其中一个是必需的。
第二个子模式以null
作为类型。因此,该模式的唯一可接受值是null
。
发布于 2022-01-19 09:45:51
您可以删除patternProperties
并将其折叠到additionalProperties
中--这需要一个模式,而不仅仅是真/假。因为patternProperties
是一个与所有内容匹配的通配符,所以那里的additionalProperties
没有添加任何值。
否则,除了声明不能有零属性的"minProperties": 1
之外,您的定义已经允许在顶层使用可选属性,而在“计划”级别,所有属性也是可选的。使用required
关键字确保属性实际存在:
参考资料:https://json-schema.org/understanding-json-schema/reference/object.html
https://stackoverflow.com/questions/70771422
复制相似问题