2017-04-06 71 views
0

我有一個下面的JSON模式片段。JSON模式如何執行數組驗證?

"attributes": { 
       "type": "array", 
       "minItems": 3, 
       "items": { 
        "type": "string", 
        "enum": [ 
         "a", 
         "b", 
         "c" 
        ] 
       } 
      } 

我希望允許所有的文件,其中將至少有3種元素在「屬性」陣列。它們的值必須是「a」,「b」和「c」,但最重要的是,我不想拒絕可能擴展該列表的文檔。 舉例來說,我想下面的代碼片段是有效的:

"attributes": ["x", "a", "b", "z", "c"] 

目前因爲有數組中的附加價值我的驗證失敗。

請指教。

回答

1

隨着草案-06您可以使用關鍵字contains

{ 
    "type": "array", 
    "minItems": 3, 
    "allOf": [ 
    { "contains": { "const": "a" } }, 
    { "contains": { "const": "b" } }, 
    { "contains": { "const": "c" } } 
    ] 
} 

隨着草案-04,你需要使用:

{ 
    "type": "array", 
    "minItems": 3, 
    "allOf": [ 
    { "not": { "items": { "not": { "enum": ["a"] } } } }, 
    { "not": { "items": { "not": { "enum": ["b"] } } } }, 
    { "not": { "items": { "not": { "enum": ["c"] } } } } 
    ] 
} 
+0

我在草稿-04上。 –

+0

它確實有效!看起來有點哈克,但它解決了我的問題。 非常感謝您的幫助@esp –

+0

切換到草稿06已經:) – esp

0

我已經找到解決我的問題:

"attributes": { 
      "type": "array", 
      "uniqueItems": true, 
      "minItems": 3, 
      "items": [ 
       {"type": "string", "enum": ["a"]}, 
       {"type": "string", "enum": ["b"]}, 
       {"type": "string", "enum": ["c"]} 
      ] 
     } 

但我不喜歡這種方法是我必須按照他們的順序指定所需的元素在架構中。 例如:"attributes": ["a", "b", "c", "z", "x"]會正常工作。但是,如果我弄亂了所需屬性的順序,驗證失敗。 "attributes": ["b", "a", "c", "z", "x"] - 無效的模式。 修好後也會很好。