首页 > 解决方案 > JSONSchema 验证包含特定项目的字符串数组

问题描述

我正在尝试指定一个必须包含特定属性的字符串数组。

我想指定验证所需的项目。
在此示例中:uuid、模板、createdOn、updatedOn。它必须是一个字符串数组。

我的架构如下所示:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "56544e3c-e197-4602-8457-2c01dc6b12c5",
  "title": "The Root Schema",
  "type": "object",
  "additionalProperties": false,
  "required": ["attributes"],
  "properties": {
    "attributes": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "enum": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"]
      },
    }
  }
}

并应对此进行验证:

{
  "attributes": ["uuid", "template", "createdOn", "updatedOn"],
},

{
  "attributes": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"],
}

但不是因为缺少项目“updatedOn”:

{
  "attributes": ["uuid", "template", "createdOn", "fields", "elements"],
}

我已经尝试了很多都没有成功。任何人都可以给我一个提示吗?

标签: jsonjsonschemajson-schema-validator

解决方案


您可以使用contains关键字来确保数组包含某个项目。

"allOf": [
  { "contains": { "const": "uuid" } },
  { "contains": { "const": "template" } },
  ...
]

推荐阅读