Enum Values in JSON Schema — Restricting to Allowed Values
Use the enum keyword in JSON Schema to restrict a field to a fixed set of allowed values. Covers strings, numbers, and mixed-type enums with practical examples.
Detailed Explanation
Restricting Values with enum
The enum keyword defines an explicit list of values that a field may hold. If the input does not exactly match one of the listed values, validation fails.
Basic String Enum
{
"status": {
"type": "string",
"enum": ["active", "inactive", "pending"]
}
}
Only the three listed strings are accepted. "Active" (capitalized) or "unknown" would be rejected.
Numeric Enum
{
"priority": {
"type": "integer",
"enum": [1, 2, 3, 4, 5]
}
}
This restricts the priority to a 1-5 scale, combining type checking with value restriction.
Mixed-Type Enum
{
"value": {
"enum": ["auto", 0, null]
}
}
When using mixed types in an enum, you can omit the type keyword entirely. The enum alone is sufficient to validate that the value matches one of the listed options.
enum vs. const
If only a single value is allowed, use const instead of a one-element enum:
{ "version": { "const": "2.0" } }
This is semantically clearer and behaves identically to "enum": ["2.0"].
Generator Behavior
Generators typically do not produce enum automatically from a single sample — they have no way to know the full set of valid values from one example. To generate enums:
- Provide multiple sample objects with different values for the same field.
- Or add the
enumconstraint manually after generation.
Best Practices
- Keep enum lists exhaustive: every valid value should be listed. If new values are added later, the schema must be updated.
- Pair
enumwithdescriptionto document what each value means. - For APIs, consider whether the enum should be open or closed — a closed enum rejects unknown values, which can break forward compatibility.
Use Case
Use enum constraints for status codes, role types, priority levels, configuration modes, or any field with a predefined set of allowed values in API contracts and configuration schemas.
Try It — JSON Schema Generator
Related Topics
JSON Schema String Constraints — minLength, maxLength, pattern
Basic Types
JSON Schema Number Constraints — minimum, maximum, multipleOf
Basic Types
Pattern Validation — Regex in JSON Schema
Advanced Patterns
oneOf, anyOf, allOf — Schema Composition in JSON Schema
Advanced Patterns
Boolean and Null Types in JSON Schema Generation
Basic Types