AJV模式验证针对对象数组

22

我正在尝试使用AJV模式验证来验证对象数组。以下是示例代码

var Ajv = require('ajv');
var schemaValidator = Ajv();

var innerSchema = {
"type" : "object",
"properties" : {
    "c" :  {
        "type" : "string"
    },
    "d" : {
        "type" : "number"
    }
},
"required" : ["c"]
}

var innerArraySchema = {
"type": "array",
"items" : {
    "#ref": innerSchema
}
}

var schema = {
"type" : "object",
"properties" : {
    "a" :  {
        "type" : "string"
    },
    "b" : {
        "type" : "string"
    },
    "obj" : innerArraySchema
},
"required" : ["a"]
}

var testSchemaValidator = schemaValidator.compile(schema);

var data = {"a": "123","b" : "abc", "obj" : [{
"d" : "ankit"
}]}


var valid = testSchemaValidator(data);

console.log(valid);

if(!valid) {
    console.log(testSchemaValidator.errors);
}

我是否有所遗漏?我不想将properties对象添加到数组定义本身中。


通过消除ref关键字解决了该问题。var innerArraySchema = { "type": "array", "items" : innerSchema } - ankit kothana
2个回答

44

使用以下方法解决了该问题:

var innerArraySchema = {
"type": "array",
"items" : innerSchema
}

1

这是$ref而不是#ref

另外请注意,您可以通过ID加载模式:

var innerArraySchema = {
  "type": "array",
  "items": {
    $ref: 'https://www.example.com/my-schema.schema.json',
  },
  "items" : innerSchema
}

请注意,以这种方式使用模式ID(URL)不会自动导入模式;您还需要使用Ajv.getSchema()Ajv.addSchema()来加载模式。
组合模式文档中有更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接