使用至少一个包含特定值的JSON Schema属性进行验证

时间:2015-08-12 01:17:44

标签: json jsonschema

我想知道我是否可以定义一个JSON模式(草案4),该模式要求至少有一个属性具有特定值。

为了说明,这是一个我希望 FAIL 验证的JSON示例:

{
    "daysOfWeek": {
        "mon": false,
        "tue": false,
        "wed": false,
        "thu": false,
        "fri": false,
        "sat": false,
        "sun": false
    }
}

但如果上述属性中的任何一个(一个或多个)设置为true,那么我才会期望 PASS 验证。

那么Schema会是什么?

{
    "daysOfWeek": {
        "type": "object",
        "properties": {
            "mon": { "type": "boolean" },
            "tue": { "type": "boolean" },
            "wed": { "type": "boolean" },
            "thu": { "type": "boolean" },
            "fri": { "type": "boolean" },
            "sat": { "type": "boolean" },
            "sun": { "type": "boolean" }
        },
        "anyOf": [{
            // ?
        }]
    }
}

非常感谢提前!

2 个答案:

答案 0 :(得分:1)

您可以使用enum关键字指定属性具有特定值。您可以将此技巧与anyOf结合使用,以获得所需的验证行为。

{
  "type": "object",
  "properties": {
    "daysOfWeek": {
      "type": "object",
      "properties": {
        "mon": { "type": "boolean" },
        "tue": { "type": "boolean" },
        "wed": { "type": "boolean" },
        "thu": { "type": "boolean" },
        "fri": { "type": "boolean" },
        "sat": { "type": "boolean" },
        "sun": { "type": "boolean" }
      },
      "anyOf": [
        {
          "properties": {
            "mon": { "enum": [true] }
          }
        },
        {
          "properties": {
            "tue": { "enum": [true] }
          }
        },
        {
          "properties": {
            "wed": { "enum": [true] }
          }
        },
        {
          "properties": {
            "thu": { "enum": [true] }
          }
        },
        {
          "properties": {
            "fri": { "enum": [true] }
          }
        },
        {
          "properties": {
            "sat": { "enum": [true] }
          }
        },
        {
          "properties": {
            "sun": { "enum": [true] }
          }
        }
      ]
    }
  }
}

答案 1 :(得分:1)

对于你在这里的案例,@ Jason的答案是好的(并且可读)。在一般情况下(你可能有任意数量的属性),有一种更简洁的方式(但不太可读):

您可以将您的要求改为“不允许所有属性都为假”,在这种情况下,架构可以是:

{
    "type": "object",
    "properties": {...},
    "not": {
        "additionalProperties": {"enum": [false]}
    }
}

additionalProperties位于子架构中,因此它未连接到根级别的properties值。因此,它适用于所有属性。

not内的子模式只有在所有属性都为false时才会通过 - 因此,只有当所有属性都为false时,外部模式才会通过。