有没有办法为未预定义的键定义草案 7 JSON 架构,但每个键都约束为枚举? json 示例将如下所示:
{
"letters": {
"a": [1, 2, 3],
"b": [2, 3]
}
}
其中
letters
对象中的键受枚举约束:键为 ["a", "b", "c"]。
我希望能够使用任意数量的键,只要它们在枚举中,这样以下 json 也可以通过:
{
"letters": {
"a": [1, 2, 3],
}
}
未预定义的键,但每个键都约束为枚举
使用
additionalProperties
创建约束为具有动态属性的枚举的对象模式
{
"type": "object",
"properties": {
"letters": {
"type": "object",
"additionalProperties": {
"enum": [1,2,3]
}
}
}
}
这将验证
{
"letters": {
"a": 2,
"ddd": 1
}
}
字母对象中的键受枚举约束:键入 ["a", "b", "c"]。
我希望能够使用任意数量的键,只要它们在枚举中即可
可能有效的关键字是
patternProperties
或 propertyNames
.
{
"type": "object",
"properties": {
"letters": {
"patternProperties": {
"a|b|c": {
"enum": [1,2,3]
}
}
}
}
}
--
这将验证
{
"letters":
"a": 1,
"b": 2,
"c": 3
}
或
这个可能很棘手,因为枚举可以定义 any JSON Schema 模式,例如:
boolean
、number
、integer
、null
、object
或 array
。这些是无效的 JSON property(键)名称。只能在 string
枚举中定义 propertyNames
模式。
{
"type": "object",
"properties": {
"letters": {
"propertyNames": {
"enum": ["a","b","c"]
},
"additionalProperties": {
"enum": [1,2,3]
}
}
}
}
这将得到验证。
{
"letters": {
"a": 1,
"b": 2,
"c": 3
}
}
如果您希望值是数字数组,则应将
additionalProperties
模式修改为
"additionalProperties": {
"type": "array",
"items": [{"type": "number"]}
}
这将验证
{
"letters": {
"a": [1, 2, 3],
}
}