Lal Asus Lal Asus - 2 months ago 7
JSON Question

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.

Answer

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