面向未来的JSON模式



是否有可能强制定义已知对象("敌人"one_answers"朋友"),而允许其他对象?

我添加了最后一个对象{"type": "object"}来显示预期的行为——但实际上最后一个对象将推翻两个定义的对象("enemy"one_answers"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个应该OK,后3个不应该OK):

[
  {"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
]

这不是很清楚你真正想要的,但你可能想在这里使用dependenciesminProperties的组合。这里使用了该关键字的两种形式:属性依赖和模式依赖。您还希望至少定义一个属性,因此是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" ]
        }
    }
}

注意这个模式仍然允许"敌人"one_answers"朋友"同时存在(你原来的模式也是如此)。为了做得更好,应该提供您希望认为有效和无效的json示例。

最新更新