How can i write the json schema if json has multiple data set

余生颓废 提交于 2019-12-20 07:44:16

问题


I am new to this json schema , i am able to write json schema if it has only one data set like below

{
    "employees": [
        {
            "id": 1,
            "name": "aaa"
        }
}

example json-schema for this is

{   
        "type" : "object",
            "required" : ["employees"],
            "properties" : {        
                "employees" : { "type" : "Array",
                                "items" : [
                                "properties" : {
                                                    "id" : {"type" : "integer"},
                                                    "name" : {"type" : "string"},                                                   
                                                },
                                            "required" : ["id","name"]
                                            ]
                                }
                            }
}

but i got stuck to write json schema in ruby if we have multiple data sets

{
    "employees": [
        {
            "id": 1,
            "name": "aaa"
        },
        {
            "id": 2,
            "name": "bbb"
        },
        {
            "id": 3,
            "name": "cccc"
        },
        {
            "id": 4,
            "name": "ddd"
        },
        {
            "id": 5,
            "name": "eeee"
        }
    ]
}

can anyone please help me to write json schema if it has multiple data sets for same schema to validate the response body


回答1:


Here is the schema you are looking for.

{
  "type": "object",
  "required": ["employees"],
  "properties": {
    "employees": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": { "type": "integer" },
          "name": { "type": "string" }
        },
        "required": ["id", "name"]
      }
    }
  }
}

You were really close. The items keyword has two forms. The value of items can be a schema or an array of schemas(1).

If items is a schema, it means that every item in the array must conform to that schema. This is the form that is useful in this case.

If the value of items is an array of schemas, it describes a tuple. For example, this schema ...

{
  "type": "array",
  "items": [
    { "type": "boolean" },
    { "type": "string" }
  ]
}

would validate this ...

[true, "foo"]
  1. http://json-schema.org/latest/json-schema-validation.html#anchor37


来源:https://stackoverflow.com/questions/32730926/how-can-i-write-the-json-schema-if-json-has-multiple-data-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!