I would like to constrain a (tuple) array in JSON-schema, and get decent error messages but so far I was unsuccessful.
The array consists of 2 items, the first is a string, and the second is an object. The properties that are allowed/required in the object depends on the string. 2 valid examples would be:
{
"color": [ "white", { "a white property": 42 }]
}
and
{
"color": [ "black", { "this is a black property": "tAttUQoLtUaE" }]
}
for reference, the type in typescript would be defined as:
type MyObject = {
color:
| ["white", {
"a white property": number
}]
| ["black", {
"this is a black property": string
}]
}
I have tried 'oneOf' (see below), and it works, but if the file is not valid, the error message is uncomprehensible. You can try this instance at jsonschemavalidator.org:
{
"color": [ "black", {
"XXX": "foo"
}]
}
My attempt:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"required": [
"color"
],
"properties": {
"color": {
"oneOf": [
{
"type": "array",
"items": [
{
"enum": [ "white"]
},
{
"type": "object",
"required": [ "a white property" ],
"additionalProperties": false,
"properties": {
"a white property": {
"type": "number"
}
}
}
]
},
{
"type": "array",
"items": [
{
"enum": ["black"]
},
{
"type": "object",
"required": [ "this is a black property" ],
"additionalProperties": false,
"properties": {
"this is a black property": {
"type": "string"
}
}
}
]
}
]
}
},
"additionalProperties": false
}
Is there a better way to express this rule?