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

fpe*_*nim 5 json contains jsonschema

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

{
  "names": [
    {
      "firstName": "Hermione",
      "lastName": "Granger"
    }, {
      "firstName": "Harry",
      "lastName": "Potter"
    }, {
      "firstName": "Ron",
      "lastName": "Weasley"
    }, {
      "firstName": "Ginevra",
      "lastName": "Weasley",
      "nickName": "Ginny"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

目前,我正在使用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"]}
        ]
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

fpe*_*nim 10

我设法弄清楚了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"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于旧版本的 json 模式规范有什么想法吗? (3认同)