58

我想制作一个 json 文件的架构。它用于一系列产品。

json 模式如下所示:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product set",
"type": "array",
"items": {
    "title": "Product",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "number"
        },
        "name": {
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
        },
        "dimensions": {
            "type": "object",
            "properties": {
                "length": {"type": "number"},
                "width": {"type": "number"},
                "height": {"type": "number"}
            },
            "required": ["length", "width", "height"]
        },
        "warehouseLocation": {
            "description": "Coordinates of the warehouse with the product",
            "$ref": "http://json-schema.org/geo"
        }
    },
    "required": ["id", "name", "price"]
}
}

该数组应至少包含一项。如何定义数组的最小值?

我需要添加最小定义吗?

4

3 回答 3

79

要设置数组中的最小项目数,请使用"minItems".

看:

https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#section-5.3.3

http://jsonary.com/documentation/json-schema/?section=keywords/Array%20validation

   {
   "$schema": "http://json-schema.org/draft-04/schema#",
   "title": "Product",
   "description": "A product from Acme's catalog",
   "type": "object",
   "properties": {
      ...
      "tags": {
          "type": "array",
          "items": {
              "type": "string"
          },
          "minItems": 1,
          "maxItems": 4,
          "uniqueItems": true
      }
  },
  "required": ["id", "name", "price"]
  }
于 2014-04-25T19:05:36.467 回答
8

看起来 v4 草案允许您正在寻找的内容。从http://json-schema.org/example1.html

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
    ...
    "tags": {
        "type": "array",
        "items": {
            "type": "string"
        },
        "minItems": 1,
        "uniqueItems": true
    }
},
"required": ["id", "name", "price"]
}

请注意,“tags”属性被定义为一个数组,其中包含最少的项目数 (1)。

于 2013-11-30T22:33:48.707 回答
8

我想不,至少在寻找工作草案时,minimum它仅适用于数值,而不是数组。

5.1。数字实例(数字和整数)的验证关键字
...
5.1.3。最小和排他最小

所以你应该对数组的 min/maxItems 很好。

于 2013-05-17T18:51:41.283 回答