小编典典

JSON模式:如何检查一个数组是否包含至少一个具有给定值属性的对象?

json

如何检查以下json中数组names中的至少一个元素是否具有nickName具有值的属性Ginny

{
  "names": [
    {
      "firstName": "Hermione",
      "lastName": "Granger"
    }, {
      "firstName": "Harry",
      "lastName": "Potter"
    }, {
      "firstName": "Ron",
      "lastName": "Weasley"
    }, {
      "firstName": "Ginevra",
      "lastName": "Weasley",
      "nickName": "Ginny"
    }
  ]
}

目前,我正在使用06版草案(此处为 FAQ )。

这是我的NOT WORKING模式:

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "title": "Complex Array",
  "description": "Schema to validate the presence and value of an object within an array.",

  "type": "object",
  "properties": {
    "names": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "string"
          },
          "lastName": {
            "type": "string"
          },
          "nickName": {
            "type": "string"
          }
        },
        "anyOf": [
          {"required": ["nickName"]}
        ]
      }
    }
  }
}

阅读 643

收藏
2020-07-27

共1个答案

小编典典

我设法用弄清楚了draft-06。在此版本中contains,添加了新的关键字。根据此规范草案:

包含

此关键字的值必须是有效的JSON模式。如果数组实例的至少一个元素对给定架构有效,则该数组实例对“包含”有效。

工作模式:

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "title": "Complex Array",

  "type": "object",
  "properties": {
    "names": {
      "type": "array",
      "minItems": 1,
      "contains": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "string"
          },
          "lastName": {
            "type": "string"
          },
          "nickName": {
            "type": "string",
            "pattern": "^Ginny$"
          }
        },
        "required": ["nickName"]
      },
      "items": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "string"
          },
          "lastName": {
            "type": "string"
          },
          "nickName": {
            "type": "string"
          }
        }
      }
    }
  }
}
2020-07-27