首页 > 解决方案 > 验证 JSON-SCHEMA 中的多个重复对象

问题描述

我想用 json-schema 验证一个 json 对象,但是那个 json 对象可以根据用户的需要多次复制它的值。

在用户创建他的 json 时,该对象的键可以根据用户的意愿重复多次。

示例 1:(带有对象的集合)

{ 
  "info":
  [
  { 
    "name":  "aaron",
    "email": "aaron.com"
  }
  ]
}

示例 1 的 JSON-SCHEMA

   {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "email": {
          "type": "string"
        }
      },
      "required": [
        "name",
        "email"
      ]
    }

示例 2:(带有 2 个对象的集合)

{ 
  "info":
  [
  { 
    "name":  "aaron",
    "email": "aaron.com"
  },

  { 
    "name":  "misa",
    "email": "misa.com"
  }
  ]
}

示例 2 的 JSON SCHEMA

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "info": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "email": {
              "type": "string"
            }
          },
          "required": [
            "name",
            "email"
          ]
        },
        {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "email": {
              "type": "string"
            }
          },
          "required": [
            "name",
            "email"
          ]
        }
      ]
    }
  },
  "required": [
    "info"
  ]
}

简而言之,我正在寻找的是一个动态 json 模式,无论集合增长多少次,它都只能使用 1 并且不会生成多个。

标签: ruby-on-railsrubyrubygemsjsonschemajson-schema-validator

解决方案


这对我有用-

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "info": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "email": {
              "type": "string"
            }
          },
          "required": [
            "name",
            "email"
          ]
        }
      ]
      "additionalItems":{
         "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "email": {
              "type": "string"
            }
          },
          "required": [
            "name",
            "email"
          ]
      }
    }
  },
  "required": [
    "info"
  ]
 }

推荐阅读