0

是否可以强制定义已知对象(“敌人”和“朋友”)而允许其他对象?

我添加了最后一个对象 {"type": "object"} 来显示预期的行为 - 但实际上最后一个对象将推翻两个定义的对象(“enemy”和“friend”),导致任何类型的对象对此模式有效。如果我删除最后一个对象,它将允许这两个对象,但没有别的。

JSON 模式(使用数组进行更快的测试):

{
  "type": "array",
  "items": {
    "anyOf": [
      {"$ref": "#/definitions/friend"},
      {"$ref": "#/definitions/enemy"},
      {"$ref": "#/definitions/future"}
    ]
  },
  "definitions": {

    "friend": {
      "type": "object",
      "properties": {
        "time": {"type": "string"},
        "value": {"type": "number", "minimum": 100}
      },
      "required": ["time", "value"],
      "additionalProperties": false
    },

    "enemy": {
      "type": "object",
      "properties": {
        "enemy": {"type": "string"},
        "color": {"type": "number"}
      },
      "required": ["enemy", "color"],
      "additionalProperties": false
    },

    "future": {
      "type": "object",
      "properties": {
        "time": {"type": "string"}
      }, "required": ["time"],
      "additionalProperties": true
    }

  }
}

JSON 示例(前 3 个应该没问题,后 3 个应该没问题):

[
  {"time": "123", "value": 100}, <- should be valid
  {"time": "1212", "value": 150}, <- should be valid
  {"enemy": "bla", "color": 123}, <- should be valid
  {"time": "1212", "value": 50}, <- should be invalid bcoz of "future"
  {"enemy": "bla", "color": "123"}, <- shouldn't be valid bcoz of "enemy" schema
  {"somethingInFuture": 123, "someFutProp": "ok"} <- should be valid
]
4

1 回答 1

0

目前还不是很清楚你真正想要什么,但你可能想在这里使用dependencies和的组合minProperties。这里使用了 this 关键字的两种形式:属性依赖和模式依赖。您还希望至少定义一个属性,因此minProperties. 所以你可以做这样的事情(注意我也分解了通用模式color;它可能是你想要的,也可能不是你想要的):

{
    "type": "object",
    "minProperties": 1,
    "additionalProperties": {
        "type": "string" // All properties not explicitly defined are strings
    },
    "properties": {
        "color": { "type": "number" }
    },
    "dependencies": {
        "enemy": "color", // property dependency
        "friend": { // schema dependency
            "properties": { "color": { "minimum": 50 } },
            "required": [ "color" ]
        }
    }
}

请注意,此架构仍然允许同时使用“敌人”和“朋友”(您的原始架构也是如此)。为了做得更好,应提供您希望认为有效和无效的示例 JSON。

于 2015-06-03T06:15:59.977 回答