Json schema does not fail if properties of schema and json file are different

Viewed 312

In using https://www.jsonschemavalidator.net/

I have a schema of:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/product.schema.json",
  "title": "Product",
  "description": "A product from Acmes catalog",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "birthday": {
      "type": "string",
      "format": "date-time"
    },
    "category": {
      "type": "string",
      "enum": [
        "Driver Qual",
        "Medical Info",
        "Personel",
        "Personnel",
        "Prev Emp Inquiry",
        "Drug-Alcohol"
      ]
    },
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        },
        "country": {
          "type": "string"
        }
      }
    }
  },
  "required": [
    "first_name",
    "last_name"
  ]
}

and a json file that is:

{
  "first_name": "George",
  "last_name": "Washington",
  "birthday": "2018-11-13T20:20:39+00:00",
  "address": {
    "street_address": "3200 Mount Vernon Memorial Highway",
    "city": "Mount Vernon",
    "state": "Virginia",
    "country": "United States",
    "category": "Personel2"
  }
}

this passes validation, but if I change the json file to: ( i.e. move the location of category to under birthday ) it fails ( as I would expect being Personel2 is not in the enum list )

{
  "first_name": "George",
  "last_name": "Washington",
  "birthday": "2018-11-13T20:20:39+00:00",
  "category": "Personel2",
  "address": {
    "street_address": "3200 Mount Vernon Memorial Highway",
    "city": "Mount Vernon",
    "state": "Virginia",
    "country": "United States"
  }
}

Why does it not fail when the category is at the end of the file ? I thought the order of the properties is irrelevant ?

1 Answers

When you move a category to an address it passes validation because for the compiller this category property doesn't have any validation, it is just an extra string property of the address property. If you add the category to an address property too, then a validation will fail or you can add "additionalProperties": false to an address validation

"address": {
      "type": "object",
       "additionalProperties": false,

in this case adding an extra category property to the address will case an error message "Property 'category' has not been defined and the schema does not allow additional properties".

But when you move a category to a root, it failes validation because a root validation schema contains a category property and it should be an enumeration.

Related