简体   繁体   中英

Json schema for array of objects doesn't validate

I have this schema for a json response

{
    "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"]
}

and I want to match this schema with this 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 schema matches the response but it also matches the schema in which the required field is this

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

I think the schema is validated against the array and the objects in the array are not validated.

The way you have it set up now, your properties key refers to the array itself, not to each item, and is being ignored (because arrays don't have properties, they just have items). You need to use the items key to validate each item in the array, like so:

{
    "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'] } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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