1
需要一個特定的項目,我有以下json
對象:陣列中的
{
"my_items": [
{ "a": "primary", n: 1 },
{ "b": "secondary", n: 2 },
{ "b": "secondary", n: 3 }
]
}
在my_items
列表中的所有項目都應該是唯一的。現在,我需要用下面的規則來驗證整個json
對象:
它可能包含與
"type": "secondary"
零個或多個項目,但它絕對必須包含一個且只有一個"type": "primary"
項目。
這怎麼可以用最新的json-schema
表示?
我拿出following:
var schema = {
"definitions": {
"primary_item": {
"type": "object",
"properties": {
"a": {
"type":"string",
"enum":["primary"]
}
}
},
"secondary_item": {
"type": "object",
"properties": {
"b": {
"type": "string",
"enum":["secondary"]
}
}
}
},
"type": "object",
"properties": {
"my_items": {
"type": "array",
"minItems": 1,
"contains": {"$ref": "#/definitions/primary_item"},
"items": {
"anyOf": [
{"$ref": "#/definitions/primary_item"},
{"$ref": "#/definitions/secondary_item"}
],
"additionalProperties": false
}
}
},
"additionalProperties": false
};
var validate = ajv.compile(schema);
test({
"my_items": [
{"a": "primary"},
{"b": "secondary"},
{"b": "secondary"}
]
});
但測試失敗,與以下錯誤:
Invalid: data.my_items[0] should NOT have additional properties, data.my_items[1] should NOT have additional properties, data.my_items[2] should NOT have additional properties
我不知道**是否只有一個**可以用兩個概念來表示:'至少有一個'+'唯一'。你怎麼看? 我覺得列表中的所有對象都是唯一的(而我的例子意味着我可能有重複,這是不正確的;我已經更新了這個問題)。 – gmile