2014-11-23 63 views
6

我試圖實現這個條件:字段是必需的基於另一個字段的值,即如果請求與「索引」:「真」存在然後「ID」所需元素:true。JSON模式條件:字段是需要基於另一個字段的值

下面是一個簡單的模式:

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "title": "test title", 
    "type": "object", 
    "properties": { 
    "data": { 
     "type": "array", 
     "items": { 
     "$ref": "#/definitions/Item" 
     }, 
     "minItems": 0 
    } 
    }, 
    "required": [ 
    "data" 
    ], 
    "definitions": { 
    "Item": { 
     "type": "object", 
     "properties": { 
     "id": { 
      "type": [ 
      "integer", 
      "string" 
      ] 
     }, 
     "type": { 
      "type": "string" 
     } 
     } 
    } 
    } 
} 

如何可以實現?

任何指針都會有幫助。

+0

[如何在JSON模式中使用依賴關係(draft-04)](http://stackoverflow.com/questions/18375506/how-to-use-dependencies-in-json-schema-draft-04 ) – jruizaranguren 2014-11-24 09:10:33

+0

[JSON模式 - 根據另一個字段的值需要指定字段]的可能重複(http://stackoverflow.com/questions/9029524/json-schema-specify-field-is-required-based-on-value -of-另一場) – buff 2016-01-22 13:05:23

回答

7

你的樣品CHEMA奇怪的是我,但在售票描述驗證情況下,你可以使用JSON瑪的這一部分:

"properties": { 
    "data": { 
     "oneOf": [ 
      { 
       "type": "object", 
       "required": [ 
        "index" 
       ], 
       "properties": { 
        "index": { 
         "type": "boolean", 
         "enum": [false] 
        } 
       } 
      }, 
      { 
       "type": "object", 
       "required": [ 
        "index", 
        "id" 
       ], 
       "properties": { 
        "index": { 
         "type": "boolean", 
         "enum": [true] 
        }, 
        "id": { 
         "type": "boolean" 
        } 
       } 
      } 
     ] 
    } 
} 

這個技巧可以幫助你,如果你想驗證一個參數,其他時候參數等於某個值。

相關問題