Json 对象数组的架构未验证

Json schema for array of objects doesn't validate

我有一个 json 响应的架构

{
    "title": "Products",
    "description": "schema for products",
    "type": "array",
    "properties": {
        "id": {
            "description": "id of a product",
            "type": "integer"
        },
        "name": {
            "description": "name of the product",
            "type": "string"
        },
        "created_at": {
            "description": "record created_at",
            "type": "string",
            "format": "date-time"
        },
        "updated_at": {
            "description": "record updated_at",
            "type": "string",
            "format": "date-time"
        }
    },
    "required": ["id", "name"]
}

我想将此架构与此 json

匹配
[{
    "id": 1,
    "name": "Cricket Ball"
}, {
    "id": 2,
    "name": "Soccer Ball"
}, {
    "id": 3,
    "name": "football ball"
}, {
    "id": 4,
    "name": "Basketball ball"
}, {
    "id": 5,
    "name": "Table Tennis ball"
}, {
    "id": 6,
    "name": "Tennis ball"
}]

此架构与响应相匹配,但它也与必填字段为 this 的架构相匹配

"required": ["ids", "names"]

我认为架构已针对数组进行了验证,但数组中的对象未经过验证。

尝试map

new_array = response.map{ |k| { 'id': k['properties']['id']['description'], 'name': k['properties']['name']['description'] } }

按照你现在的设置方式,你的 properties 键指的是数组本身,而不是每个项目,并且被忽略了(因为数组没有属性,它们只有项目) .您需要使用 items 键来验证数组中的每一项,如下所示:

{
    "title": "Products",
    "description": "schema for products",
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "id": {
            "description": "id of a product",
            "type": "integer"
        },
        "name": {
            "description": "name of the product",
            "type": "string"
        },
        "created_at": {
            "description": "record created_at",
            "type": "string",
            "format": "date-time"
        },
        "updated_at": {
            "description": "record updated_at",
            "type": "string",
            "format": "date-time"
        }
      },
      "required": ["id", "name"]
    }
}