JSON模式:如何检查一个数组是否包含至少一个具有给定值属性的对象? [英] JSON Schema: How to check that an array contains at least one object with a property with a given value?

查看:354
本文介绍了JSON模式:如何检查一个数组是否包含至少一个具有给定值属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I check in the following json that at least one element in the array names has a property nickName with the value Ginny?

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

当前,我正在使用06版草案(常见问题解答这里).

Currently I'm using the draft-06 version (FAQ here).

这是我的不工作"模式:

This is my NOT WORKING schema:

{
  "$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"]}
        ]
      }
    }
  }
}

推荐答案

我设法使用draft-06弄清了这一点.在此版本上,添加了新的关键字contains.根据该草案规范:

I managed to figure it out using draft-06. On this version a new keyword contains was added. According to this draft specification:

包含

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

The value of this keyword MUST be a valid JSON Schema. An array instance is valid against "contains" if at least one of its elements is valid against the given schema.

工作模式:

{
  "$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"
          }
        }
      }
    }
  }
}

这篇关于JSON模式:如何检查一个数组是否包含至少一个具有给定值属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆