简体   繁体   中英

Validate all elements of an array

I'm trying to validate a JSON within its associated schema.

I'm validating using the following website: https://www.jsonschemavalidator.net/

My test data looks like this

[
  {
    "testString": "string value",
    "testInt": 1
  },
  {
    "testString": "another string value",
    "testInt": 2
  }
]

And the schema is defined as follow

{
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "testString": {
          "type": "string"
        },
        "testInt": {
          "type": "integer"
        }
      },
      "required": [
        "testString",
        "testInt"
      ],
      "additionalProperties": false
    }
  ]
}

It works well for the given example, however if I add an unexpected attribute into the second element it's not detected as an error. Otherwise it is if I add it into the first element

So this works (detected as wrong JSON)

[
  {
    "testString": "string value",
    "testInt": 1,
    "unexpectedAttribute": "unexpected value"
  },
  {
    "testString": "another string value",
    "testInt": 2
  }
]

But this doesn't works (detected as valid JSON)

[
  {
    "testString": "string value",
    "testInt": 1
  },
  {
    "testString": "another string value",
    "testInt": 2,
    "unexpectedAttribute": "unexpected value"
  }
]

I also tried with this website but I have the same result, so I think that I may have forgotten something into my schema.

Does anybody already faced the same issue?

you schema has a bug, remove extra [] from items. When you are using [], you have to add rules for each element of array. In you cases only the first element has rules, anothers not. You can change the second item of your items array any way, it will not generate any error, since it is not validated at all.

{
  "type": "array",
  "items": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "testString": {
        "type": "string"
      },
      "testInt": {
        "type": "integer"
      }
    },
    "required": [
      "testString",
      "testInt"
    ]
  }
}

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