2016-04-25 82 views
3

我有輸入JSON像下面,條件JSON模式驗證基於屬性值

{ 
    "results": [ 
    { 
     "name": "A", 
     "testA": "testAValue" 
    } 
    ] 
} 

的條件是,如果「名稱」的值是「A」,然後「種皮」應該是所需的場如果'name'的值是'B',那麼'testB'應該是必填字段。

這是JSON模式我試着和它的工作不正常,

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "object", 
    "required": [ 
    "results" 
    ], 
    "properties": { 
    "results": { 
     "type": "array", 
     "oneOf": [ 
     { 
      "$ref": "#/definitions/person" 
     }, 
     { 
      "$ref": "#/definitions/company" 
     } 
     ] 
    } 
    }, 
    "definitions": { 
    "person": { 
     "type": "object", 
     "required": [ 
     "name", 
     "testA" 
     ], 
     "properties": { 
     "name": { 
      "type": "string", 
      "enum": [ 
      "A" 
      ] 
     }, 
     "testA": { 
      "type": "string" 
     } 
     } 
    }, 
    "company": { 
     "type": "object", 
     "required": [ 
     "name", 
     "testB" 
     ], 
     "properties": { 
     "name": { 
      "type": "string", 
      "enum": [ 
      "B" 
      ] 
     }, 
     "testB": { 
      "type": "string" 
     } 
     } 
    } 
    } 
} 

試圖與「依賴條件」在JSON模式太多,但沒能找到正確的解決方案。

任何與示例JSON模式的幫助/解決方法來實現上述用例表示讚賞。

+0

的可能的複製[如何使用JSON模式依賴(草案-04)](http://stackoverflow.com/questions/18375506/how-to-use-dependencies-in-json-schema-草案-04) – jruizaranguren

回答

4

Your're close。您的oneOf需要位於items關鍵字中。

{ 
    "type": "array", 
    "items": { 
     "oneOf": [ 
      { "$ref": "#/definitions/person" }, 
      { "$ref": "#/definitions/company" } 
     ] 
    } 
}