Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJV schema validation for array of objects

I am trying to validate array of objects using AJV schema validation. 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.

like image 590
ankit kothana Avatar asked May 23 '17 11:05

ankit kothana


People also ask

How do I validate a JSON file with a schema?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What is a schema validation?

An API schema defines which API requests are valid based on several request properties like target endpoint and HTTP method. Schema Validation allows you to check if incoming traffic complies with a previously supplied API schema.

What is allOf in JSON Schema?

allOf: (AND) Must be valid against all of the subschemas. anyOf: (OR) Must be valid against any of the subschemas. oneOf: (XOR) Must be valid against exactly one of the subschemas.


1 Answers

Resolved the issue by using:

var innerArraySchema = {
"type": "array",
"items" : innerSchema
}
like image 198
ankit kothana Avatar answered Sep 22 '22 05:09

ankit kothana