constant (v5 proposal) - sgpinkus/json-schema GitHub Wiki

THIS WIKI IS OBSOLETE. PLEASE SEE THE NEW JSON-SCHEMA-ORG/JSON-SCHEMA-SPEC REPOSITORY.


NOTE: This proposal has been migrated to https://github.com/json-schema-org/json-schema-spec/issues/58


Proposed keywords

  • constant

Purpose

For ordinary use, this would be equivalent to a single-valued enum, simply tidier.

The only real difference comes in its behaviour with $data-substitution. $data-subsitution would be allowed for this keyword, which means that this keyword is not capable of specifying literal values of the form: {"$data":...}, because these would be interpreted as $data-substitutions.

However, literal values of this form can still be specified using enum, so there is no loss of functionality.

Values

The value of this keyword would be any value - however, it would be subject to $data-substitution.

Validation

Instances are only valid if they are exactly equal to the value of this keyword.

Example

Simple constant

{
    "type": "object",
    "properties": {
        "five": {
            "constant": 5
        }
    }
}

Valid: {}, {"five": 5} Invalid: {"five": 0}, {"five": "5"}

Using $data to specify equality

{
    "type": "object",
    "properties": {
        "a": {"type": "string"},
        "b": {
            "constant": {"$data": "1/a"}
        }
    },
    "required": ["a", "b"]
}

Valid: {"a": "foo", "b": "foo"}, {"a": "bar", "b": "bar"} Invalid: {"a": "foo", "b": "bar"}

Concerns

Similarity to enum

Unless $data is being used, the same effect can be obtained using fewer actual characters:

  • {"constant":"whatever"} - 23 characters
  • {"enum":["whatever"]} - 21 characters

However, when used in combination with $data, it opens up possibilities that are not otherwise available.