Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a jsonschema so that it validates all objects in array?

I'm trying to validate a JSON input using json-schema but it does not work like I need it to.

I have the following input JSON (part of it):

[
  {
    "admin_state": "disabled"
  },
  {
    "state": "disabled"
  }
]

And the following json-schema (part of it as well):

{
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "admin_state": {
          "type": "string",
          "default": "enabled",
          "enum": [
            "disabled",
            "enabled"
          ]
        }
      },
      "additionalProperties": false
    }
  ],
  "minItems": 1
}

I want the validation to fail because of the "state" property that should not be allowed (thanks to the "additionalProperties": false option)

However, I can add/change anything in the second item in the array, validation is always successful. When I change anything in the first item, validation fails (as expected).

What did I miss?

Thanks for your help!

like image 340
calvinvinz Avatar asked Mar 16 '18 11:03

calvinvinz


1 Answers

JSON Schema draft 7 states...

If "items" is a schema, validation succeeds if all elements in the array successfully validate against that schema.

If "items" is an array of schemas, validation succeeds if each element of the instance validates against the schema at the same position, if any.

In your schema, items is an array, which means you were only applying the subschem in that array to the first element of your instance's array. Simply remove the square braces from items, and your subschema will be applicabale to ALL items in the instance.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "admin_state": {
        "type": "string",
        "default": "enabled",
        "enum": [
          "disabled",
          "enabled"
        ]
      }
    },
    "additionalProperties": false
  },
  "minItems": 1
}
like image 170
Relequestual Avatar answered Oct 24 '22 06:10

Relequestual