Json 架构:验证数组

Json Schema: Validating Arrays

我正在尝试验证包含两个键 tagsparameters 的架构,这两个键旨在成为任意键值对的数组。但是,出于某种原因,我无法得到 任何东西 我为这两个密钥指定的验证失败(我正在使用 nodejs 库 ajv)。

这是架构定义:

var cfStackSchema = {
  name: { type: "string" },
  application: { type: "string" },
  account: { type: "string" },
  environment: { type: "string" },
  tags: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  parameters: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  deps: { type: "array", items: { type: "string" } },
  required: ["name", "account", "environment", "parameters", "application"]
};

这里是一个测试对象。我在这里将 parameters 作为一个简单的字符串传递,打算使其验证失败,但它实际上通过了:

var spec = { name: "test", 
            account: "test", 
            environment: "test",
            parameters: "test",
            application: "test"
          };

这是我用来验证的代码:

  var ajv = new Ajv({ useDefaults: true });
  var validate = ajv.compile(cfStackSchema);
  if (!validate(spec)) {
    throw new Error('Stack does not match schema!')
  }

您只需要将属性放在 properties 对象中

var cfStackSchema = {
  properties: {
    name: { type: "string" },
    application: { type: "string" },
    account: { type: "string" },
    environment: { type: "string" },
    tags: { 
      type: "array",
      items: {
        type: "object",
        patternProperties: {
          "^[a-zA-z0-9]$": { type: "string" }
        },
        additionalProperties: false
      },
      additionalItems: false
    },
    parameters: { 
      type: "array",
      items: {
        type: "object",
        patternProperties: {
          "^[a-zA-z0-9]$": { type: "string" }
        },
        additionalProperties: false
      },
      additionalItems: false
    },
    deps: { type: "array", items: { type: "string" } },
  },
  required: ["name", "account", "environment", "parameters", "application"]
};