7

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!

Relequestual
  • 11,631
  • 6
  • 47
  • 83
calvinvinz
  • 73
  • 3

1 Answers1

10

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
}
Relequestual
  • 11,631
  • 6
  • 47
  • 83
  • Makes total sense now, thanks for your clear explanation.I just tested it and it works perfectly! – calvinvinz Mar 16 '18 at 12:45
  • Feel free to upvote answers as well as accept them =] Also feel free to join the JSON Schema slack should you have any questions which you cannot ask here (or just join anyway). – Relequestual Mar 16 '18 at 12:46
  • @Relequestual you saved me a lot of time. Online schema generatoros had added square brackets everywhere. – shyammakwana.me Feb 27 '19 at 10:48
  • This just saved me some future catastrophic data cleanup! Thank you! – Ollie Dec 15 '21 at 18:17