如何为属性编写JSON模式取决于其他字段的值?
问题描述:
这是我的要求:当num == 0时,a是必需的;当num == 1时,b是必需的。如何为属性编写JSON模式取决于其他字段的值?
{
"type": "object",
"properties": {
"num": { "type": "integer" },
"a": { "type": "string" },
"b": { "type": "string" }
}
"required": [ "num" ]
}
答
我目前的解决方案:
{
"type": "object",
"oneOf": [
{"$ref": "#/definitions/0"},
{"$ref": "#/definitions/1"},
],
"definitions": {
"0": {
"properties": {
"num": {"enum": [0]},
"a": {"type": "string"}
},
"required": ["num", "a"]
},
"1": {
"properties": {
"num": {"enum": [1]},
"b": {"type": "string"}
},
"required": ["num", "b"]
}
}
}
我使用jsonschema,它返回is not exactly on from <#definitions/0>
。这不是我想要的。我希望它可以返回有关细节的消息,如a
是必需的。
答
改进版本:
{
"type": "object",
"properties": {
"num": { "type": "integer" },
"a": { "type": "string" },
"b": { "type": "string" }
}
"required": [ "num" ],
"dependencies": {
"a": {
"properties": {
"num": {
"enum": [0]
}
}
},
"b": {
"properties": {
"num": {
"enum": [1]
}
}
}
}
}
什么你试试? –
我还没有找到值依赖的解决方案。 – Hom