Json 架构中第一个元素的不同必需属性?
Json Schema Different required properties for first element in array?
假设我想验证 json 中的数组,其中只有第一个元素具有可选的 属性。数组中的其余项目将需要 属性.
schema.json
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": {
"oneOf": [
{ "$ref": "./first.json" },
{ "$ref": "./rest.json" }
]
}
}
}
}
first.json
{
"type": "object",
"properties": {
"y": { "type": "number" },
"z": { "type": "boolean" }
},
"required": ["y"]
}
rest.json
{
"type": "object",
"properties": {
"y": { "type": "number" },
"z": { "type": "boolean" }
}
}
有效json:
{
"x": [
{ "z": true },
{ "y": 4, "z": true },
{ "y": 5 }
]
}
无效json:
{
"x": [
{ "z": true },
{ "z": true }, // this line would be invalid
{ "y": 5 }
]
}
但是,当我提供 y 值时,上面的设置给了我“多个模式匹配”。另一种方法可能是:
schema.json
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": [
{ "$ref": "./first.json" },
{ "$ref": "./rest.json" }
]
}
}
}
此模式对数组中的前两个元素执行我想要的操作(第一个不需要 y 但第二个需要 y),但不对第二个之后的对象应用任何模式。
items
关键字有两种形式。第一个是您正在使用的模式形式。第二种是数组形式。数组形式采用一组模式,其中每个模式都适用于它在实例中的对应项。例如,当给定一个具有两个模式的数组时,它会根据第一个模式验证实例中的第一个项目,并根据第二个模式验证第二个项目。
还有一个additionalItems
关键字可以与items
的数组形式一起使用。任何与 items
中的架构不对应的项目都会根据 additionalItems
架构进行验证。使用前面的示例和 items
中的两个模式,一个具有三个项目的实例将根据 additionalItems
模式评估它的第三个项目。
因此,我们可以使用 items
的数组形式将“./first.json”应用于第一项,并使用 additionalItems
将“./[=27”应用于=]" 到数组的其余部分。
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": [{ "$ref": "./first.json" }],
"additionalItems": { "$ref": "./rest.json" }
}
}
}
假设我想验证 json 中的数组,其中只有第一个元素具有可选的 属性。数组中的其余项目将需要 属性.
schema.json
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": {
"oneOf": [
{ "$ref": "./first.json" },
{ "$ref": "./rest.json" }
]
}
}
}
}
first.json
{
"type": "object",
"properties": {
"y": { "type": "number" },
"z": { "type": "boolean" }
},
"required": ["y"]
}
rest.json
{
"type": "object",
"properties": {
"y": { "type": "number" },
"z": { "type": "boolean" }
}
}
有效json:
{
"x": [
{ "z": true },
{ "y": 4, "z": true },
{ "y": 5 }
]
}
无效json:
{
"x": [
{ "z": true },
{ "z": true }, // this line would be invalid
{ "y": 5 }
]
}
但是,当我提供 y 值时,上面的设置给了我“多个模式匹配”。另一种方法可能是:
schema.json
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": [
{ "$ref": "./first.json" },
{ "$ref": "./rest.json" }
]
}
}
}
此模式对数组中的前两个元素执行我想要的操作(第一个不需要 y 但第二个需要 y),但不对第二个之后的对象应用任何模式。
items
关键字有两种形式。第一个是您正在使用的模式形式。第二种是数组形式。数组形式采用一组模式,其中每个模式都适用于它在实例中的对应项。例如,当给定一个具有两个模式的数组时,它会根据第一个模式验证实例中的第一个项目,并根据第二个模式验证第二个项目。
还有一个additionalItems
关键字可以与items
的数组形式一起使用。任何与 items
中的架构不对应的项目都会根据 additionalItems
架构进行验证。使用前面的示例和 items
中的两个模式,一个具有三个项目的实例将根据 additionalItems
模式评估它的第三个项目。
因此,我们可以使用 items
的数组形式将“./first.json”应用于第一项,并使用 additionalItems
将“./[=27”应用于=]" 到数组的其余部分。
{
"type": "object",
"properties": {
"x": {
"type": "array",
"items": [{ "$ref": "./first.json" }],
"additionalItems": { "$ref": "./rest.json" }
}
}
}