Reputation: 313
I have a JSON Object with two properties (among others), that are category
and subcategory
,I have a function to get the list of categories and another one to get the subcategories for a given category.
So my schema looks something like this:
{
"type": "array",
"items": {
"type": "obect",
"properties": {
"category": {
"type": "string",
"enum": getCategories()
},
"subcategory": {
"type": "string",
"enum": getSubcategories(category)
}
}
}
Note: One subcategory is in only one main category
The list of categories is large and I want to check with json schema that the category and subcategory are valid, so I wonder if there is a way of doing so.
Using npm package for node js
Let's assume i have the categories A and B with [A1,A2]
and [B1,B2]
, if the json to validate has the category A I want to check that the subcategory is in [A1,A2]
not in [A1,A2,B1,B2]
Tried if-else statements from this other post but as I mentioned the list is large and doesn't look like a good practice at all
Upvotes: 0
Views: 982
Reputation: 53996
At the moment, if
/then
constructs would be needed to specify the subcategory values based on category:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": [ ... ]
},
"subcategory": {
"type": "string",
},
},
"allOf": [
{
"if": {
"properties": {
"category": { "const": "option1" },
}
},
"then": {
"properties": {
"subcategory": {
"enum": [ ... ]
}
}
}
},
{
"if": {
"properties": {
"category": { "const": "option2" },
}
},
"then": {
"properties": {
"subcategory": {
"enum": [ ... ]
}
}
}
},
{ ... }
]
}
}
However, there is a proposal to add a new keyword for the next draft specification which would shorten the syntax considerably: https://github.com/json-schema-org/json-schema-spec/issues/1082
Upvotes: 1