JSON 架构 Draft-07 架构 用于枚举中的动态键

问题描述 投票:0回答:1

有没有办法为未预定义的键定义草案 07 JSON 架构,但每个键都限制为枚举? json 示例将如下所示:

{
    "letters": {
        "a": [1, 2, 3],
        "b": [2, 3]
    }
}

letters
对象中的键受枚举约束:键为 ["a", "b", "c"]。

我希望能够使用任意数量的键,只要它们在枚举中,这样以下 json 也可以通过:

{
    "letters": {
        "a": [1, 2, 3],
    }
}
jsonschema
1个回答
0
投票

未预定义的键,但每个键都约束为枚举

使用

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],
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.