简体   繁体   中英

Can “additionalProperties” apply to nested objects in JSON Schema?

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?

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
  ...
}

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