diff --git a/pages/understanding-json-schema/reference/enum.md b/pages/understanding-json-schema/reference/enum.md index 9cbfab50e..bb660e4ea 100644 --- a/pages/understanding-json-schema/reference/enum.md +++ b/pages/understanding-json-schema/reference/enum.md @@ -9,50 +9,97 @@ next: url: /understanding-json-schema/reference/const --- + The `enum` [keyword](../../learn/glossary#keyword) is used to restrict a value to a fixed set of values. -It must be an array with at least one element, where each element is -unique. +It must be an array with at least one element, where each element is unique. + +Below are several examples demonstrating its usage. + +### Basic Example: Street Light Colors + +This example demonstrates how to validate that the `color` property of a street light is either "red", "amber", or "green". + +```json +// props { "isSchema": true } +{ + "properties": { + "color": { + "enum": ["red", "amber", "green"] + } + } +} +``` +```json +// props { "indent": true, "valid": true } +{ "color": "red" } +``` + +```json +// props { "indent": true, "valid": false } +{ "color": "blue" } +``` -The following is an example for validating street light colors: +### Extended Example: Accepting Multiple Data Types + +Enums can be used without explicitly setting a data type, allowing different types of values. +In the following example, the schema is extended to include `null` (to represent an "off" state) and the number 42. ```json // props { "isSchema": true } { - "enum": ["red", "amber", "green"] + "properties": { + "color": { + "enum": ["red", "amber", "green", null, 42] + } + } } ``` + ```json // props { "indent": true, "valid": true } -"red" +{ "color": null } ``` + +```json +// props { "indent": true, "valid": true } +{ "color": 42 } +``` + ```json // props { "indent": true, "valid": false } -"blue" +{ "color": 0 } ``` -You can use `enum` even without a type, to accept values of different -types. Let\'s extend the example to use `null` to indicate \"off\", and -also add 42, just for fun. + +### Additional Example: Mixed Types for Shape ```json // props { "isSchema": true } { - "enum": ["red", "amber", "green", null, 42] + "properties": { + "shape": { + "enum": ["circle", "square", 1, null] + } + } } ``` + ```json // props { "indent": true, "valid": true } -"red" +{ "shape": "circle" } ``` + ```json // props { "indent": true, "valid": true } -null +{ "shape": 1 } ``` + ```json // props { "indent": true, "valid": true } -42 +{ "shape": null } ``` + ```json // props { "indent": true, "valid": false } -0 -``` \ No newline at end of file +{ "shape": "triangle" } +```