jsonschema:只有一个默认元素的元素列表

jsonschema: List of elements with exactly one default element

我在 jsonschema 验证方面遇到了一些困难。我有一个包含一些预定义字段的元素列表。这些元素中的一个应该定义一个 default 字段。所以像这样:

{
    "items": [
        {
            "id": 1,
            "name": "item1"
        },
        {
            "id": 2,
            "name": "item2",
            "default": true
        },
        {
            "id": 3,
            "name": "item3"
        }
    ]
}

如果 none 项具有 default 字段或多个,则验证将失败。有任何想法吗?谢谢!

您需要使用 JSON 架构草案 2019-09 中的 maxContains 关键字。

首先,为了使用min/max包含,你需要定义contains

An array instance is valid against "contains" if at least one of its
elements is valid against the given schema.

接下来,您需要同时设置 [maxContains][2] to 1`。

An array instance is valid against "maxContains" if the number of
elements that are valid against the schema for "contains"
[json-schema] is less than, or equal to, the value of this keyword.

If "contains" is not present within the same schema object, then this keyword has no effect.

你不需要设置 minContains 因为它是隐含的 1 通过使用 contains.

A value of 0 is allowed, but is only useful for setting a range of
occurrences from 0 to the value of "maxContains". A value of 0 with
no "maxContains" causes "contains" to always pass validation.

{
  "$schema": "http://json-schema.org/draft/2019-09/schema",
  "properties": {
    "items": {
      "contains": {
        "required": ["default"]
      },
      "maxContains": 1
    }
  }
}

这是一个使用您的实例 JSON 进行演示的现场演示:https://www.jsonschemavalidator.net/s/p0RQ2hvY