Using AJv to validate Json schema

Hello everyone, i’m having a trouble when i use ajv to validate Json schema. This is my test script:

const expectSchema = {
“definitions”: {
“Welcome”: {
“type”: “object”,
“additionalProperties”: false,
“properties”: {
“id”: {
“type”: “integer”
},
“name”: {
“type”: “string”
},
“type”: {
“type”: “string”
},
“available”: {
“type”: “boolean”
}
},
“required”: [
“available”,
“id”,
“name”,
“type”
],
“title”: “Welcome”
}
}
}

var Ajv = require(‘ajv’)
var ajv = new Ajv({logger: console})
pm.response.json().forEach(function(book){
console.log(ajv.errors)
pm.test(‘Schema is valid’, function() {
pm.expect(ajv.validate(expectSchema, book)).to.be.true;
});
})
And here is examples json when i get them from url:
[
{
“id”: 1,
“name”: “The Russian”,
“type”: “fiction”,
“available”: true
},
{
“id”: 2,
“name”: “Just as I Am”,
“type”: “non-fiction”,
“available”: false
},
{
“id”: 3,
“name”: “The Vanishing Half”,
“type”: “fiction”,
“available”: true
},
{
“id”: 4,
“name”: “The Midnight Library”,
“type”: “fiction”,
“available”: true
},
{
“id”: 5,
“name”: “Untamed”,
“type”: “non-fiction”,
“available”: true
},
{
“id”: 6,
“name”: “Viscount Who Loved Me”,
“type”: “fiction”,
“available”: true
}
]

All my tests are passing when it is run, but when i change type of any properties (example: i change type of id to string or boolean, type of name into integer) my tests still pass. Could you guys explain it to me? thank you sm.

Hi @phuongphuong99

You won’t need to import AJV like that, it’s already built into Postman.
As explained (about halfway through) in this video; JSON Schema validation in Postman - YouTube


Just been playing around with this and even though the schema appears to validate I think your schema is incorrect.

It doesn’t recognise 1 as an int and there are a few other things that didn’t seem to work right.

I knocked up a new schema with an online JSON to schema converter… the result looks like this;
Note: snipped to keep it short…

const expectSchema = {
    "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "available": {
          "type": "boolean"
        }
      },
      "required": [
        "id",
        "name",
        "type",
        "available"
      ]
    }
]
}

The validation looks like this;

and an invalid value;

Hope this helps.

1 Like

thanks for your help. I edited my schema and it worked. thank you so much