Home > Back-end >  Why are booleans valid JSON schemas?
Why are booleans valid JSON schemas?

Time:06-24

I'm looking at JSON schema's meta schemas and according to the Core/Validation Dialect meta-schema the JSON true and false are valid JSON schemas. What is the point of this?

You can see that they validate properly here.

CodePudding user response:

It's true that a boolean schema, in its entirety, is not terribly useful, except perhaps as a placeholder ("in the future, we will have a more defined data structure; in the meantime, all values are acceptable"). But schemas can also contain schemas, and then we can start to express more meaningful things.

Consider describing data thusly:

  • the top level of the data must be an object.
  • the object must include the properties "alpha" and "beta".
  • the value of "alpha" must be a string.
  • the value of "beta" can be anything.
  • the property "gamma" may exist, and its value can be anything.
  • the property "epsilon" must not be present.
  • if there any other properties present, they must be numbers.

We would define the JSON schema like this:

{
  "type": "object",
  "required": ["alpha", "beta"],
  "properties": {
    "alpha": {
      "type": "string"
    },
    "beta": true,
    "gamma": true,
    "epsilon": false,
  },
  "additionalProperties": {
    "type": "number"
  }
}

Now, as you can see, under the "properties" and "additionalProperties" keywords we have several subschemas. Some of the subschemas contain more keywords ("type" in this case), but some of the subschemas are just plain old booleans. They're conveying something of meaning: "this condition is always valid" or "this condition is always invalid".

  • Related