简体   繁体   English

对象数组的AJV模式验证

[英]AJV schema validation for array of objects

I am trying to validate array of objects using AJV schema validation. 我正在尝试使用AJV模式验证来验证对象数组。 Below is the sample code 下面是示例代码

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);
}

Is there something that I am missing here. 有什么我在这里失踪的东西。 I would not like to add the properties object inside the array definition itself. 我不想在数组定义本身中添加属性对象。

Resolved the issue by using: 使用以下方法解决了该问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM