我的 JSON 数据模型有一个对象,该对象具有一组属性,其中可能只有一个或没有,其他属性也有自己的约束。有没有办法像 this example 那样不重复地做到这一点? ?
下面是我使用 Node.js + ajv 实现这一目标的最接近的简单示例。
var Ajv = require('ajv'),
ajv = new Ajv();
var schema = {
type: 'object',
properties: {
id: {type: 'string'},
a: {type: 'integer'},
b: {type: 'integer'}
},
required: ['id'],
oneOf: [
{required: ['a']},
{required: ['b']}
],
additionalProperties: false
};
// invalid
var json1 = {
id: 'someID',
a: 1,
b: 3
};
// valid
var json2 = {
id: 'someID',
b: 3
};
// valid
var json3 = {
id: 'someID',
a: 1
};
// valid
var json4 = {
id: 'someID'
};
var validate = ajv.compile(schema);
console.log(validate(json1)); // false
console.log(validate(json2)); // true
console.log(validate(json3)); // true
console.log(validate(json4)); // false
最佳答案
您必须以不同的方式思考问题。不要试图表达模式可以是什么,而是尝试表达模式不能是什么。这里有两个选项。
一种说法是,“a”和“b”不能同时存在。
{
"type": "object",
"properties": {
"id": { "type": "string" },
"a": { "type": "integer" },
"b": { "type": "integer" }
},
"required": ["id"],
"not": { "required": ["a", "b"] },
"additionalProperties": false
}
另一种构建问题的方法是,如果“a”存在,则“b”不能存在。并且,如果“b”存在,则“a”不能存在。
{
"type": "object",
"properties": {
"id": { "type": "string" },
"a": { "type": "integer" },
"b": { "type": "integer" }
},
"required": ["id"],
"dependencies": {
"a": { "not": { "required": ["b"] } },
"b": { "not": { "required": ["a"] } }
},
"additionalProperties": false
}
关于json - JSON 模式中的一组属性中的一个或一个都没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794079/