如何在 json 模式中将 required 添加到子数组?

How to add required to sub array in a json schema?

我正在创建一个 json 架构来定义具有数据类型的必要数据。有一些数据需要设置到 required 字段中。但是没有在它的文档中找到如何做。

对于此 json 架构:

{
  "type": "object",
  "required": [
    "version",
    "categories"
  ],
  "properties": {
    "version": {
      "type": "string",
      "minLength": 1,
      "maxLength": 1
    },
    "categories": {
      "type": "array",
      "items": [
        {
          "title": {
            "type": "string",
            "minLength": 1
          },
          "body": {
            "type": "string",
            "minLength": 1
          }
        }
      ]
    }
  }
}

json喜欢

{
   "version":"1",
   "categories":[
      {
         "title":"First",
         "body":"Good"
      },
      {
         "title":"Second",
         "body":"Bad"
      }
   ]
}

我也想将 title 设置为必填项。它在一个子数组中。如何在 json 架构中设置它?

您的架构有一些问题。我假设您使用的是 JSON 架构草案 2019-09。

首先,您希望 items 是一个对象,而不是数组,因为您希望它应用于数组中的每个项目。

If "items" is a schema, validation succeeds if all elements in the
array successfully validate against that schema.

If "items" is an array of schemas, validation succeeds if each
element of the instance validates against the schema at the same
position, if any.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-02#section-9.3.1.1

其次,如果 items 的值应该是模式,您需要将其视为模式本身。

如果我们从您的 items 数组中取出项目作为模式,它实际上不会做任何事情,您需要将它嵌套在 properties 关键字中...

{
  "properties": {
    "title": {
      "type": "string",
      "minLength": 1
    },
    "body": {
      "type": "string",
      "minLength": 1
    }
  }
}

最后,现在你的items关键字值是一个模式(subschema),你可以添加任何你可以正常使用的关键字,比如required,和你之前做的一样。

{
  "required": [
    "title"
  ],
  "properties": {
    ...
  }
}