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

jsonschema - dynamic properties with static properties

我有一个模式来验证 json。

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

等等...

这个,我可以用oneOff来定义。对于所有其他 "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"
  ]
}

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

例如:

以下 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"
  }
}

如何实现?

最后一个子模式中 attr 的模式可以是:

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

或者,您可以使用下一个 JSON-schema 版本提案中的 "switch" 关键字代替 "oneOf":http://epoberezkin.github.io/ajv/keywords.html#switch-v5-proposal

在Ajv中实现了(我是作者)