2016-04-25 83 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" } 
     ] 
    } 
}