面向未来的JSON模式

时间:2015-06-02 20:47:12

标签: json json-schema-validator

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

我添加了最后一个对象{“type”:“object”}来显示预期的行为 - 但实际上最后一个对象将否决两个定义的对象(“敌人”和“朋友”)导致任何类型的对象对此架构有效。如果我删除最后一个对象,它将允许两个对象,但没有别的。

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
]

1 个答案:

答案 0 :(得分:0)

目前还不是很清楚你真正想要的是什么,但你可能想在这里使用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" ]
        }
    }
}

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