问题
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?
回答1:
See, jsonSchema attribute conditionally required, for a description of four strategies for conditional constraints. Here they are in order of which strategy produces the best error messages.
dependencies
: This is a very specific constraint, so it tends to have great error messages. Unfortunately, this doesn't work in your situation.if
/then
: This is going produce the best messages in your case.Implication: This produces pretty good error messages, but not quite as good as
if
/then
.if
/then
was added in draft-07. If you can't use draft-07 or higher, this is your best bet.Enum: This is the one you are using and it produces awful errors as you have seen. This is the worst option for error messaging.
来源:https://stackoverflow.com/questions/59976752/best-way-to-make-conditional-arrays-in-json-schema-with-decent-error-messages