Home > other >  Enforcing properties of an object to be from the listed ones in a JSON Schema
Enforcing properties of an object to be from the listed ones in a JSON Schema

Time:11-25

How can I enforce the "object" property only to allow the listed properties be part of it and not something else, especially an empty key ""?

{
  "type": "object",
  "properties": {
    "object": {
      "type": "object",
      "properties": {
        "property1": {
          "type": "string"
        },
        "property2": {
          "type": "string"
        },
        "property3": {
          "type": "string"
        }
      },
      "uniqueItems": true
    }
  }
}

CodePudding user response:

I believe, what you are looking for is "additionalProperties": false.

Below is your schema with additionalProperties added. See here to try it out: https://www.jsonschemavalidator.net/s/RDGrQvL6

Note that I had to remove the extra "object" wrapper from your schema to make it work.

{
  "type": "object",
  "properties": {
    "property1": {
      "type": "string"
    },
    "property2": {
      "type": "string"
    },
    "property3": {
      "type": "string"
    }
  },
  "additionalProperties": false
}

CodePudding user response:

Daniel's answer is correct and "additionalProperties": false is the right thing that I needed, but here is the code in terms of what I actually wanted to achieve with the nested object.

{
  "type": "object",
  "properties": {
    "object": {
      "type": "object",
      "properties": {
        "property1": {
          "type": "string"
        },
        "property2": {
          "type": "string"
        },
        "property3": {
          "type": "string"
        }
      },
      "uniqueItems": true,
      "additionalProperties": false // will not allow any other property other than 'property1', 'property2' or 'property3' as part of the nested object "object".
    }
  }
}
  • Related