Warm tip: This article is reproduced from serverfault.com, please click

JSON Schema reporting error only for first element of array

发布于 2018-07-27 11:37:05

I have the below JSON document.

[
    {
        "name": "aaaa",
        "data": {
            "key": "id",
            "value": "aaaa"
        }
    },
    {
        "name": "bbbb",
        "data": {
            "key": "id1",
            "value": "bbbb"
        }
    }
]

Below is the JSON Schema I have created for the above content.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "data": {
          "type": "object",
          "properties": {
            "key": {
              "type": "string",
              "enum": [
                "id",
                "temp",             
              ]
            },
            "value": {
              "type": "string",
            }
          },
          "required": [
            "key",
            "value"
          ]
        }
      },
      "required": [
        "name",
        "data"
      ]
    }
  ]
}

As per the schema, the value of data.key is invalid for second item in the array. but any online schema validator does not find that. If we use different value in first array element, it throws the excepted error.

I assume that my schema is wrong somehow. what I expect is that any child items of the array should be reported if they have values out of the enum list.

Questioner
Purus
Viewed
0
Bot 2021-10-07 15:24:50

It's an easy mistake to make, so don't beat yourself up about this one!

items can be an array or an object. If it's an array, it validates the object at that position in the instance array. Here's an excerpt from the JSON Schema spec (draft-7)

The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.

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.

JSON Schema (validation) draft-7 items

Removing the square braces provides you with the correct schema...

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": 
    {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "data": {
          "type": "object",
          "properties": {
            "key": {
              "type": "string",
              "enum": [
                "id",
                "temp",             
              ]
            },
            "value": {
              "type": "string",
            }
          },
          "required": [
            "key",
            "value"
          ]
        }
      },
      "required": [
        "name",
        "data"
      ]
    }
  
}