const : Any
const
AnyValidation succeeds if the instance is equal to this keyword’s value.
Value | This keyword must be set to a JSON value |
---|---|
Kind | Assertion |
Applies To | Any |
Base Dialect | 2020-12 |
Changed In | None |
Introduced In | Draft 6 |
Vocabulary | Validation |
Specification | https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6.1.3 |
Metaschema | https://json-schema.org/draft/2020-12/meta/validation |
Official Tests | draft2020-12/const.json |
Default | None |
Annotation | None |
Affected By | None |
Affects | None |
Also See |
|
The const
keyword (short for “constant”) restricts instances to a single
specific JSON value of any type.
Best Practice
Constraining instances to a constant value by definition implies the given JSON type. Therefore, combining this keyword with the
type
keyword is redundant (or even
invalid if types don’t agree), and considered an
anti-pattern.
Common Pitfall
There are programming languages, such as JavaScript, that cannot distinguish between integers and real numbers. To accomodate for those cases, JSON Schema considers a real number with a zero fractional part to be equal to the corresponding integer. For example, in JSON Schema,
1
is
considered to be equal to 1.0
.
Examples
A schema that constrains instances to an integer constant value
Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"const": 5
}
Valid
The desired integer value is valid
Instance
5
Valid
The real value representation of the desired integer value is valid
Instance
5.0
Invalid
Any other number value is invalid
Instance
1234
Invalid
Any other non-number value is invalid
Instance
"Hello"
A schema that constrains instances to a complex object value
Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"const": { "name": "John Doe", "age": 30 }
}
Valid
The object instance that equals the desired value is valid
Instance
{ "name": "John Doe", "age": 30 }
Invalid
Any other object value is invalid
Instance
{ "name": "Jane Doe", "age": 30 }
Invalid
Any other non-object value is invalid
Instance
30