'In json schema, how to define an enum with description of each elements in the enum?
In json schema, I can simply define a code list using "enum" with a list of code that is available, for example:
{
"type": "object",
"properties": {
"group": {
"type":"string",
"$ref": "#/definitions/Group"
}
},
"definitions": {
"Group": {
"enum": ["A","B"]
}
}
}
And the following payload would be valid:
{
"group": "B"
}
However, I try to provide the description in the schema to the user where "A" = "Group A", "B" = "Group B". Something like:
{
"type": "object",
"properties": {
"group": {
"type":"string",
"$ref": "#/definitions/Group"
}
},
"definitions": {
"Group": {
"enum": [
{"code":"A",
"description": "Group A"
},
{"code":"B",
"description": "Group B"
}
]
}
}
}
But I don't want to change the structure of the payload (no "description" field needed) The description is more for documentation purposes that users can refer to. Is there a good practice that can be used here?
Thank you
Solution 1:[1]
You can use anyOf
with const
instead of enum
. Then you can use title
or description
for documentation.
{
"anyOf": [
{
"const": "A",
"title": "Group A"
},
{
"const": "B",
"title": "Group B"
}
]
}
Solution 2:[2]
It depends on your tool-chain. For example the jsonschema2md allows to use meta:enum
attribute for descriptions:
{
"type": "object",
"properties": {
"group": {
"type":"string",
"$ref": "#/definitions/Group"
}
},
"definitions": {
"Group": {
"enum": ["A", "B"],
"meta:enum": {
"A": "Group A",
"B": "Group B"
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jason Desrosiers |
Solution 2 | eNca |