JSON 模式要求不存在值

use*_*321 5 validation json jsonschema

我想对我的架构执行 JSON 验证,该架构有四个属性:

  • group
  • partition
  • select
  • features

如果使用 或grouppartitionfeatures需要。如果使用select,则被features禁止(请注意,这似乎与这个问题中的情况不同- 我不想将其设置为features“不需要”,但如果包含它,则会出现验证错误。

所以我的三个选择是:

  • groupfeatures
  • partitionfeatures
  • select并不是features

我将它们编码为:

"oneOf": [
  { "required": [ "group", "features" ] },
  { "required": [ "partition", "features" ] },
  { "required": [ "select" ] }
]
Run Code Online (Sandbox Code Playgroud)

但我不知道如何适当地强制features排除在最后一个选项之外 - 或者这是否有可能?

Vel*_*uha 1

您可以定义多个模式,其中任何一个都有效

   {
        "anyOf": [
            { "$ref": "#/definitions/group" },
            { "$ref": "#/definitions/partition" },
            { "$ref": "#/definitions/select" },
        ]
    }
Run Code Online (Sandbox Code Playgroud)

对于选择,您可以定义 schema,并将additionalProperties 设置为 false,如下所示

{
  "type": "object",
  "properties": {
    "select": {"type": "string"}
  },
  "additionalProperties": false
}
Run Code Online (Sandbox Code Playgroud)

然后你会得到这样的错误:

ValidationError:不允许使用其他属性