[英]Json Schema oneOf , not working as expected
我正在創建一個 json 模式,目的是生成單個產品代碼數組或產品代碼數組數組。 簡而言之,我希望能夠返回 productCodes: [12224, 444444] 或 productCodesArray: [[12222,55555],[11111,99999]] 結果。 我嘗試了一種解決方案,該解決方案部分有效,但兩者都可以。 被)允許。 我可能誤讀了規范。 我怎樣才能做到這一點? 我嘗試使用 oneOf,這是我的解決方案:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id":"https://examples.com/schemas/my-array-schema",
"type":"object",
"required": ["productCodesResult"],
"properties": {
"additionalItems": false,
"productCodesResult": {
"type": "object",
"properties": {
"oneOf": {
"reasons": {
"$ref": "#/definitions/productCodesDef"
},
"reasonsArray": {
"$ref": "#/definitions/productCodesArrayDef"
}
}
}
}
},
"definitions": {
"productCodesDef": {
"type": "object",
"required": ["productCodes"],
"properties":{
"productsIds": {
"type": "array",
"items": {
"type": "integer",
"minItems": 1
}
}
}.
},
"productCodesArrayDef": {
"type": "object",
"required": ["reasonsArray"],
"properties":{
"productsCodesArray": {
"type": "array",
"items": {
"type": "array",
"items":{
"type": "integer",
"minItems": 1
}
}
}
}
}
}
}
用Ajv測試了這個。 在productCodes
屬性級別指定oneOf
。 添加兩個選項,一個接受字符串數組( string[]
),另一個接受字符串數組( string[][]
)。
const schema = {
type: 'object',
required: ['productCodes'],
properties: {
productCodes: {
type: 'array',
oneOf: [
{
type: 'array',
minItems: 1,
items: {
type: 'string',
},
},
{
type: 'array',
minItems: 1,
items: {
type: 'array',
minItems: 1,
items: {
type: 'string',
},
},
},
],
},
},
};
無需為屬性賦予不同的名稱,只需將其productCodes
。 在上面的示例中,我將其設為必需,因此傳遞一個空對象將無效。
import Ajv from 'ajv';
const data = {
// productCodes: ['123', '345'],
productCodes: [
['123', '345'],
['123', '345'],
],
};
const validate = this.ajv.compile(schema);
const valid = validate(data);
console.log(valid);
如果出於任何要求,屬性必須具有不同的名稱,則將它們定義為 2 個不同的屬性。 在根級別上使用oneOf
可以使它們互斥。 productCodes
或productCodesArray
必須存在。
const schema = {
type: 'object',
required: [],
properties: {
productCodes: {
type: 'array',
minItems: 1,
items: {
type: 'string',
},
},
productCodesArray: {
type: 'array',
minItems: 1,
items: {
type: 'array',
minItems: 1,
items: {
type: 'string',
},
},
},
},
oneOf: [
{ type: 'object', required: ['productCodes'] },
{ type: 'object', required: ['productCodesArray'] },
],
};
作為替代方案,您也可以使用allOf
和not
來執行此操作。
const schema = {
type: 'object',
required: [],
properties: {
productCodes: { ... }
productCodesArray: { ... }
},
allOf: [
{
not: {
type: 'object',
required: ['productCodes', 'productCodesArray'],
},
},
],
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.