jsonschema - 具有静态属性的动态属性

时间:2016-10-28 09:24:36

标签: json jsonschema

我有一个架构来验证json。

对于某些属性,我需要它们具有某些类型的值。

  • 如果“attr”属性为“a”,则“val”属性应为“整数”
  • 如果“attr”属性为“x”,则“val”属性应为“boolean”
  • 如果“attr”属性为“b”,则“val”属性应为“string” 格式“ipv4”

依旧......

这个,我可以用oneOff来定义。对于所有其他“attr”属性,我需要它们具有某种格式,有点像捕获所有,“val”属性为“string”。

  • 如果“attr”匹配模式,则“val”属性应为“string”。

可以这样做。

这是我目前的架构。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "name": {
      "title": "name",
      "type": "string"
    },
    "attribute": {
      "title": "attributes",
      "type": "object",
      "$ref": "#/definitions/expr",
    }
  },
  "definitions": {
    "expr": {
      "properties": {
        "attr": {
          "title": "attribute"
        },
        "val": {
          "title": "val"
        }
      },
      "required": ["val", "attr"],
      "oneOf": [
        {
          "properties": {
            "attr": {"enum": ["a","b"]},
            "val": {"type": "integer"}
          }
        },
        {
          "properties": {
            "attr": {"enum": ["x"]},
            "val": {"type": "boolean"}
          }
        },
        {
          "properties": {
            "attr": {"pattern": "^[-A-Za-z0-9_]*$", "maxLength": 255},
            "val": {"type": "string"}
          }
        }
      ]
    }
  },
  "additionalProperties": false,
  "required": [
    "name",
    "attribute"
  ]
}

问题是我试图限制值类型的属性,也匹配catchall格式。所以当我期待一个整数值时,它传递的是字符串值。

例如:

以下json将根据oneOff的第一项

传递架构
{
  "name": "shouldpass",
  "attribute": {
    "attr": "a",
    "val": 1
  }
}

以下json将根据oneOff的最后一项传递。

{
  "name": "shouldpass2",
  "attribute": {
    "attr": "h",
    "val": "asd"
  }
}

下面的json应该失败,基于oneOff的第一项,但它也在传递,因为它匹配oneOff的最后一项。

{
  "name": "shouldfail",
  "attribute": {
    "attr": "a",
    "val": "string"
  }
}

如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

最后一个子模式中attr的架构可能是:

{
    "pattern": "^[-A-Za-z0-9_]*$",
    "not": { "enum": ["a", "b", "x"] },
    "maxLength": 255
}

或者,而不是" oneOf"你可以使用" switch"来自下一个JSON架构版本提案的关键字:http://epoberezkin.github.io/ajv/keywords.html#switch-v5-proposal

它在Ajv中实现(我是作者)。

相关问题