首页 > 解决方案 > 如何通知 Json 模式它必须在其数组中至少具有一种类型的对象,但其他类型是可选的

问题描述

我正在为工作更新 JSON 模式。

对于 json 数组,我们有

"accountsInfo": [{
    "type":"ADMIN",
    "firstName":"Bill",
    "lastName":"Cipher",
    "emailAddress":"bcipher@gfalls.com"

}, {
    "type":"USER"
    "firstName":"Bugs",
    "lastName":"Bunny",
    "emailAddress":"whats@updoc.org"
}]

USER 类型对于此模式必须是可选的,数组中至少需要 1 个 ADMIN 类型。我怎样才能做到这一点?

这是架构文件的一部分。它使用 Json Schema 7。

  "accountsInfo": {
    "type": "array",
    "uniqueItems": true,
    "minItems": 2,
    "items": [
      {
        "type": "object",
        "required": [
          "type",
          "firstName",
          "lastName",
          "emailAddress"
        ],
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "ADMIN",
              "USER"
            ]
          },
          "firstName": {
            "type": "string",
            "$ref": "#/definitions/non-empty-string"
          },
          "lastName": {
            "type": "string",
            "$ref": "#/definitions/non-empty-string"
          },
          "emailAddress": {
            "type": "string",
            "format": "email"
          }
        }
      }
    ]
  }

标签: jsonjsonschemajson-schema-validator

解决方案


您可以为此使用“包含”关键字。在伪代码中:“数组必须包含(至少一个)成功评估此模式的项目”。

作为 and 的兄弟关键字"type": "object""items": { ... }添加:

"contains": {
  "properties": {
    "type": {
      "const": "ADMIN"
    }
  }
}

此外,您的"items"关键字中有一个错误:如果您打算让该子模式匹配所有项目,而不仅仅是第一个项目,请删除模式周围的额外数组。“items”的数组形式依次将数据中的每一项与架构中的每一项进行匹配,并且您只需为第一项指定架构,因此第一项之后的所有项都可以是任何内容。

"items": { .. schema .. }不是"items": [ { .. schema .. } ]


推荐阅读