在JSON模式中用体面的错误消息制作条件数组的最佳方法 [英] best way to make conditional arrays in json schema with decent error messages
问题描述
我想用JSON模式约束一个(元组)数组,并得到不错的错误消息,但到目前为止我没有成功.
I would like to constrain a (tuple) array in JSON-schema, and get decent error messages but so far I was unsuccessful.
该数组由2个项目组成,第一个是字符串,第二个是对象.对象中允许/需要的属性取决于字符串. 2个有效的例子是:
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 }]
}
和
{
"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
}]
}
我尝试了"oneOf"(请参见下文),并且可以运行,但是如果文件无效,则错误消息将变得令人难以理解. 您可以在jsonschemavalidator.org上尝试此实例:
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"
}]
}
我的尝试:
{
"$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?
推荐答案
请参见 jsonSchema属性,以描述四种条件约束策略.在这里,它们是按照哪种策略产生最佳错误消息的顺序进行的.
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
:这是一个非常具体的约束,因此往往会出现严重的错误消息.不幸的是,这不适用于您的情况.
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
:这将产生适合您情况的最佳消息.
if
/then
: This is going produce the best messages in your case.
含义:这会产生非常好的错误消息,但不如if
/then
好.在草案07中添加了if
/then
.如果您不能使用Draft-07或更高版本,这是您最好的选择.
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.
这篇关于在JSON模式中用体面的错误消息制作条件数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!