JSON 架构中一组属性的 1 个或 none

1 or none of a set of properties in JSON schema

我的 JSON 数据模型有一个具有一组属性的对象,其中可能只有 1 个或 none 以及其他具有自己约束的属性。有没有办法像 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
}