My JSON data model has an object with a set of properties from which only 1 or none may be present as well other properties with their own constraints. Is there a way to do this without repetition as in this example?
Below is a simple example of as close as I have gotten to achieve this using 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