5

in JSON-schema, one can require certain keys in an object, see this example, taken from the json schema docs:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "email": { "type": "string" },
    "address": { "type": "string" },
    "telephone": { "type": "string" }
  },
  "required": ["name", "email"]
}

I need the opposite: Is there a way to forbid or prevent a certain key from being in an object? Specifically, I want to prevent users from having an empty key inside an object:

{
    "": "some string value"
}
S.A.
  • 1,819
  • 1
  • 24
  • 39

2 Answers2

7

You can exclude certain keys by name with:

{
 "not": {
  "anyOf": [
    { "required": [ "property1" ] },
    { "required": [ "property2" ] },
    { "required": [ "property3" ] },
    ...
  ]
}

https://json-schema.org/understanding-json-schema/reference/combining.html

Ether
  • 53,118
  • 13
  • 86
  • 159
0

Next to excluding keys with the not syntax (see answer by Ether), it is possible to achieve the goal with property-names.

In the following example, all keys have to map to a string URI. We furthermore exclude all keys that are not alphanumeric (via pattern), or don't have a specific length (via minLength). Other than that, we have no restrictions on keys.

"SomeKeyToBeValidated": {
  "type": "object",
  "properties": { },
  "propertyNames": {
    "type": "string",
    "minLength": 1,
    "pattern": "^[a-zA-Z0-9]*$"
  },
  "additionalProperties": {
    "type": "string",
    "format": "uri"
  }
}
S.A.
  • 1,819
  • 1
  • 24
  • 39