所以模式的要求是,
- 必须有"must_1",
- 必须是其中之一;
- "key_2"值为true (boolean)
- "key_3">
- 当"key_2"值为false或不存在,"key_3"必须存在
- 可能有"optional_4"(这实际上是相当多的额外的键,所有这些将被描述)
- 可能没有任何描述的键
所以这些应该通过
"pass_1": {
"must_1": 1,
"key_2": false,
"key_3": "ewe"
},
"pass_2": {
"must_1": 2,
"key_3": "ewe"
},
"pass_3": {
"must_1": 3,
"key_2": true
},
这个应该会失败
"fail_1": {
"must_1": 7,
"key_2": false
},
My attempt so far
然而这通过了"fail_1">
{
"type": "object",
"additionalProperties": false,
"required": ["must_1"],
"dependentRequired": {
"not": {
"key_2": ["key_3"]
}
},
"properties": {
...
}
}
这个真难倒我了。
复制粘贴代码(模式和测试)
我一直使用jsonschemalint作为我的比较工具
// My current none-working schema
{
"type": "object",
"patternProperties": {
"[^\s]+": {
"type": "object",
"additionalProperties": false,
"required": ["must_1"],
"dependentRequired": {
"not": {
"key_2": ["key_3"]
}
},
"properties": {
"must_1": {
"type": "number"
},
"key_2": {
"type": "boolean"
},
"key_3": {
"type": "string"
},
"optional_4": {}
}
}
}
}
// Tests, tests with "pass_#" should pass, tests with "fail_#" should fail :)
// 1-6 pass tests, 1-7 fail tests
{
"pass_1": {
"must_1": 1,
"key_2": false,
"key_3": "ewe"
},
"pass_2": {
"must_1": 2,
"key_3": "ewe"
},
"pass_3": {
"must_1": 3,
"key_2": true
},
"pass_4": {
"must_1": 4,
"key_2": false,
"key_3": "ewe",
"optional_4": "optional"
},
"pass_5": {
"must_1": 5,
"key_3": "ewe",
"optional_4": "optional"
},
"pass_6": {
"must_1": 6,
"key_2": true,
"optional_4": "optional"
},
"fail_1": {
"must_1": 7,
"key_2": false
},
"fail_2": {
"must_1": 1,
"key_2": false,
"key_3": "ewe",
"undescribed_5": "undescribed"
},
"fail_3": {
"must_1": 2,
"key_3": "ewe",
"undescribed_5": "undescribed"
},
"fail_4": {
"must_1": 3,
"key_2": true,
"undescribed_5": "undescribed"
},
"fail_5": {
"must_1": 4,
"key_2": false,
"key_3": "ewe",
"optional_4": "optional",
"undescribed_5": "undescribed"
},
"fail_6": {
"must_1": 5,
"key_3": "ewe",
"optional_4": "optional",
"undescribed_5": "undescribed"
},
"fail_7": {
"must_1": 6,
"key_2": true,
"optional_4": "optional",
"undescribed_5": "undescribed"
}
}
我得出的解决方案通过了所有测试。可能不是最好的实现
{
"type": "object",
"additionalProperties": false,
"required": ["must_1"],
"if": {
"properties": {
"key_2": {
"const": false
}
}
},
"then": {
"required": ["key_3"]
},
"properties": {
...
}