【问题标题】:JSON Schema: How to check that an array contains at least one object with a property with a given value?JSON Schema:如何检查一个数组是否包含至少一个具有给定值的属性的对象?
【发布时间】:2018-04-18 21:43:37
【问题描述】:

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

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

目前我使用的是 draft-06 版本(FAQ here)。

这是我的 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"]}
        ]
      }
    }
  }
}

【问题讨论】:

  • 您需要将 JSON 转换为字典格式,然后使用 dict["parameterName"] != nil 进行检查。

标签: json contains jsonschema


【解决方案1】:

我设法使用draft-06 解决了这个问题。在此版本中,添加了一个新关键字 contains。根据这个草稿specification

包含

此关键字的值必须是有效的 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"
          }
        }
      }
    }
  }
}

【讨论】:

  • 对旧版本的 json 模式规范有什么想法吗?
猜你喜欢
  • 2018-02-16
  • 2018-03-21
  • 2021-12-26
  • 1970-01-01
  • 2015-11-04
  • 2018-06-09
  • 2020-05-07
  • 1970-01-01
相关资源
最近更新 更多