我想用JSON模式约束一个(元组)数组,并得到不错的错误消息,但到目前为止,我没有成功。
该数组由2个项目组成,第一个是字符串,第二个是对象。对象中允许/需要的属性取决于字符串。2个有效的例子是:
{
"color": [ "white", { "a white property": 42 }]
}
和
{
"color": [ "black", { "this is a black property": "tAttUQoLtUaE" }]
}
供参考,打字稿中的类型将定义为:
type MyObject = {
color:
| ["white", {
"a white property": number
}]
| ["black", {
"this is a black property": string
}]
}
我已经尝试过'oneOf'(请参见下文),并且可以使用,但是如果文件无效,则错误消息将变得令人难以理解。您可以在jsonschemavalidator.org上尝试此实例:
{
"color": [ "black", {
"XXX": "foo"
}]
}
我的尝试:
{
"$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
}
是否有更好的方式表达此规则?
请参见jsonSchema attribute conditionally required,以获取关于条件约束的四种策略的描述。在这里,它们按哪种策略产生最佳错误消息的顺序进行。
[dependencies
:这是一个非常具体的约束,因此它往往会出现大量错误消息。不幸的是,这不适用于您的情况。
if
/ then
:这将产生您所需要的最佳消息。
Implication:这会产生非常好的错误消息,但不及if
/ then
。在草案07中添加了if
/ then
。如果您不能使用Draft-07或更高版本,这是您最好的选择。
Enum:这是您正在使用的那个,如您所见,它会产生可怕的错误。这是错误消息传递的最糟糕的选择。