繁体   English   中英

对象数组的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"
}]

该模式与响应匹配,但也与其中必填字段是此模式的匹配

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

我认为架构是针对数组验证的,数组中的对象并未验证。

现在设置的方式, 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"]
    }
}

尝试map

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM