在 json 模式中制作条件数组并带有正确错误消息的最佳方法
best way to make conditional arrays in json schema with decent error messages
我想在 JSON-schema 中约束一个(元组)数组,并得到不错的错误消息,但到目前为止我没有成功。
数组由2项组成,第一项是字符串,第二项是对象。对象中 allowed/required 的属性取决于字符串。
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
}
有没有更好的表达方式?
有关条件约束的四种策略的描述,请参阅 。此处按哪种策略产生最佳错误消息的顺序排列。
dependencies
:这是一个非常具体的约束,所以它往往有很大的错误信息。不幸的是,这不适用于您的情况。
if
/then
:这将在您的案例中产生最好的信息。
含义:这会产生非常好的错误消息,但不如 if
/then
好。 if
/then
是在 draft-07 中添加的。如果您不能使用 draft-07 或更高版本,这是您最好的选择。
Enum:这是您正在使用的那个,它会产生如您所见的可怕错误。这是错误消息的最差选择。
我想在 JSON-schema 中约束一个(元组)数组,并得到不错的错误消息,但到目前为止我没有成功。
数组由2项组成,第一项是字符串,第二项是对象。对象中 allowed/required 的属性取决于字符串。 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
}
有没有更好的表达方式?
有关条件约束的四种策略的描述,请参阅
dependencies
:这是一个非常具体的约束,所以它往往有很大的错误信息。不幸的是,这不适用于您的情况。if
/then
:这将在您的案例中产生最好的信息。含义:这会产生非常好的错误消息,但不如
if
/then
好。if
/then
是在 draft-07 中添加的。如果您不能使用 draft-07 或更高版本,这是您最好的选择。Enum:这是您正在使用的那个,它会产生如您所见的可怕错误。这是错误消息的最差选择。