2013-11-20 41 views
6

我想定義一個json模式來限制數組中的對象的屬性。json模式驗證具有anyOf和oneOf要求的對象數組

我至今是:

{ 
    "title":"myCollection", 
    "properties":{ 
     "things":{ 
      "type":"array", 
      "items":[{ 
       "title":"thingObj", 
       "type":"object", 
       "properties":{ 
        "name":{ 
         "type":"string" 
        }, 
        "code":{ 
         "type":"string" 
        }, 
        "type":{ 
         "type":"string", 
         "enum":["dog","cat"] 
        }, 
        "rate":{ 
         "type":"number" 
        }, 
        "value":{ 
         "type":"number" 
        } 
       }, 
       "anyOf":[{ 
        "properties":{ 
         "name":{ 
          "type":"string" 
         } 
        },"required":["name"] 
       },{ 
        "properties":{ 
         "code":{ 
          "type":"string" 
         } 
        },"required":["code"] 
       },{ 
        "properties":{ 
         "type":{ 
          "type":"string", 
          "enum":["new","existing"] 
         } 
        },"required":["type"] 
       }], 
       "oneOf":[{ 
        "properties":{ 
         "rate":{ 
          "type":"number" 
         } 
        }, 
        "required":["rate"] 
       },{ 
        "properties":{ 
         "value":{ 
          "type":"number" 
         } 
        }, 
        "required":["value"] 
       }], 
       "additionalProperties":false 
      }] 
     } 
    } 
} 

現在給出以下jsonobj:

{ 
    "things": [ 
     { 
      "name": "tabby", 
      "code": "meeow", 
      "type": "cat", 
      "value": 20 
     }, 
     { 
      "name": "k9", 
      "code": "woofer", 
      "type": "dog", 
      "rate": 15 
     } 
    ] 
} 

json schema validator提供了一個有效的迴應,但這個驗證似乎只適用於第一個元素陣列。如果刪除anyOf子句中包含的所有字段或第一個元素上的oneOf子句,則驗證將失敗。第二個數組元素上的相同值不會引起所需的失敗。我如何確保對每個數組成員運行驗證?

回答

13

這是因爲你有(偶然)使用「元組打字」。當"items"的值是一個數組並且它的模式與數組中的特定位置匹配時啓用此功能。

如果您將"items"(在您的模式中)更改爲簡單模式(不是模式數組),那麼它將以相同方式驗證所有項目。

相關問題