如何在JSON模式中表达多个可选属性的全部或全部?

时间:2017-06-06 16:51:04

标签: jsonschema

我想表示存在所有可选属性或不存在任何属性。例如

{
}  

{
    "a" : 1,
    "b" : 2
}  

应该都有效,但

{
    "a" : 1
}  

{
    "b" : 2
}  

应该都是无效的。

2 个答案:

答案 0 :(得分:1)

更简单的方法:

{
"properties:" {
  "a" : {"type" : "integer"},
  "b" : {"type" : "integer"}
},
"dependencies" : {
  "a" : ["b"],
  "b" : ["a"]
}
}

答案 1 :(得分:0)

这里是满足要求的模式:

{
    "type": "object",
    "properties": {
        "a": {
            "type": "integer"
        },
        "b": {
            "type": "integer"
        }
    },
    "oneOf": [{
        "required": ["a", "b"]
    }, {
        "not": {
            "anyOf": [{
                "required": ["a"]
            }, {
                "required": ["b"]
            }]
        }
    }],
    "additionalProperties": false
}

另一种方法是在JSON中表达属性,如

{
    "parent": {
        "a": 1,
        "b": 2
    }
}

父母是否存在,如果存在,则总是有a和b:

{
    "type": "object",
    "properties": {
        "parent": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "integer"
                },
                "b": {
                    "type": "integer"
                }
            },
            "required": ["a", "b"],
            "additionalProperties": false
        }

    },
    "additionalProperties": false
}