是否可以在JSON Schema中使用替代方案?在XSD中,使用xs:alternative
元素可以实现这一点。
例如,请参阅:How to use alternatives in XML Schema 1.1
更新1:
这是我想用JSON架构描述的示例JSON:
{
"actions": [
{
"type": "basic",
"param1": "value"
},
{
"type": "extended",
"param1": "value",
"param2": "blah"
}
]
}
要求:
actions
可能包含任意数量的项目basic
操作必须包含param1
属性extended
操作必须包含param1
和param2
属性答案 0 :(得分:3)
自Draft04以来,有一种类似的机制,具有更好的语义:oneOf,anyOf,allOf和not,关键字。
假设您正在寻找一个独有的"替代",这将是使用oneOf的json-schema示例:
{
"actions" : {
"type" : "array",
"items" : {
"oneOf" : [{
" $ref " : "#/definitions/type1 "
}, {
" $ref " : "#/definitions/type2 "
}
]
}
},
" definitions " : {
" type1 " : {
" type " : " object ",
"properties": {
"param1":{"type":"string"}
},
"required":["param1"]
},
" type2 " : {
" type " : " object ",
"properties": {
"param2":{"type":"string"},
"param3":{"type":"string"}
},
"required":["param2","param3"]
}
}
}