Can "additionalProperties" apply to nested objects in JSON Schema?

Viewed 1221

I'm developing an application that accepts the following JSON:

{
  "gd": { "enabled": true, "show_counts": true },
  "ra": { "enabled": true }
}

I've developed a JSON Schema that validates this input, allowing for some keys to be optional, others required, and some minimum number of properties. It works well and looks like this:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "gd": {
      "type": "object",
      "required": [ "enabled" ],
      "additionalProperties": false,
      "properties": {
        "enabled": { "type": "boolean" },
        "show_counts": { "type": "boolean" }
      }
    },
    "ra": {
      "type": "object",
      "required": [ "enabled" ],
      "additionalProperties": false,
      "properties": {
        "enabled": { "type": "boolean" }
      }
    }
  },
  "minProperties": 1
}

One thing that annoys me is that each object redundantly specifies "additionalProperties": false. I would like to specify once, at the top level, that nowhere in the JSON document should any properties not specified in the schema be allowed.

Is that possible?

1 Answers

In the latest draft (2019-09), you can do this, by defining a "base schema" that all schemas derive from:

{
  $defs: {
    base_object: {
      unevaluatedProperties: false
    },
  },
  $ref: '#/$defs/base_object',
  type: 'object',
  // additionalProperties: false does not need to be stated here
  ...
}
Related