如何使用 avj 和 postman 验证 json 架构如何使用、架构、postman、avj

2023-09-07 10:28:45 作者:*~風情萬種の青щα

我正在尝试验证如下所示的 json:

I'm trying to validate the following json that looks like this:

{
    "errors": false,
}

在邮递员上使用这个:

var Ajv = require('ajv'),
    ajv = new Ajv({logger: console, coerceTypes: false}),
    schema = {

        "errors": {
                "type": "number"
            }
    };


pm.test('Schema is valid', function() {
    var error = pm.response.json()['errors'];
    console.log("this is error: " +error);
    pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});

pm.test('Schema is valid different way', function() {
    var error = pm.response.json()['errors'];
    console.log("this is error: " +error);
    var validate = ajv.compile(schema);
    pm.expect(validate(pm.response.json())).to.be.true;
});

但它总是通过,即使我的错误对象是 boolean 而不是 number.我做错了什么?

but it's always passing, even though my errors object is a boolean and not a number. What am I doing wrong?

注意:日志如下所示

this is error: false

推荐答案

可以在 Postman 中使用 avj 查看 json schema,如下:

You can check json schema using avj in Postman as follows:

    var Ajv = require('ajv'),
    ajv = new Ajv({logger: console}),
    schema = {
        "properties": {
            "errors": {
                "type": "boolean"
            }
        }
    };

pm.test('Schema is valid', function() {
    var error = pm.response.json()['errors'];
    pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});

数据:

{
    "errors": false
}

结果:通过

数据:

{
    "errors": true
}

结果:通过

数据:

{
    "errors": 123
}

结果:失败

另一种方式

pm.test('Schema is valid', function() {
   pm.expect(typeof(pm.response.json().errors) === "boolean").to.be.true;
});