9
9
url : /understanding-json-schema/reference/const
10
10
---
11
11
12
- The ` enum ` [ keyword] ( ../../learn/glossary#keyword ) is used to restrict a value to a fixed set of values.
13
- It must be an array with at least one element, where each element is
14
- unique.
12
+ The ` enum ` keyword in JSON Schema allows you to restrict a value to a set of predefined options.
13
+ It requires an array with at least one unique element, and any value validated against this schema must exactly match one of the specified values.
15
14
16
- The following is an example for validating street light colors:
15
+ Below are several examples demonstrating its usage.
16
+
17
+ ### Basic Example: Street Light Colors
18
+
19
+ This example demonstrates how to validate that the ` color ` property of a street light is either "red", "amber", or "green".
17
20
18
21
``` json
19
22
// props { "isSchema": true }
@@ -35,9 +38,10 @@ The following is an example for validating street light colors:
35
38
{ "color" : " blue" }
36
39
```
37
40
38
- You can use ` enum ` even without a type, to accept values of different
39
- types. Let\' s extend the example to use ` null ` to indicate \" off\" , and
40
- also add 42, just for fun.
41
+ ### Extended Example: Accepting Multiple Data Types
42
+
43
+ Enums can be used without explicitly setting a data type, allowing different types of values.
44
+ In the following example, the schema is extended to include ` null ` (to represent an "off" state) and the number 42.
41
45
42
46
``` json
43
47
// props { "isSchema": true }
@@ -62,5 +66,39 @@ also add 42, just for fun.
62
66
63
67
``` json
64
68
// props { "indent": true, "valid": false }
65
- 0
66
- ```
69
+ { "color" : 0 }
70
+ ```
71
+
72
+
73
+ ### Additional Example: Mixed Types for Shape
74
+
75
+ ``` json
76
+ // props { "isSchema": true }
77
+ {
78
+ "properties" : {
79
+ "shape" : {
80
+ "enum" : [" circle" , " square" , 1 , null ]
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ ``` json
87
+ // props { "indent": true, "valid": true }
88
+ { "shape" : " circle" }
89
+ ```
90
+
91
+ ``` json
92
+ // props { "indent": true, "valid": true }
93
+ { "shape" : 1 }
94
+ ```
95
+
96
+ ``` json
97
+ // props { "indent": true, "valid": true }
98
+ { "shape" : null }
99
+ ```
100
+
101
+ ``` json
102
+ // props { "indent": true, "valid": false }
103
+ { "shape" : " triangle" }
104
+ ```
0 commit comments