简体   繁体   English

如何使用AVJ和邮递员验证JSON模式

[英]How to validate json schema using avj and postman

I'm trying to validate the following json that looks like this: 我正在尝试验证如下所示的以​​下json:

{
    "errors": false,
}

using this on postman: 在邮递员上使用它:

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

but it's always passing, even though my errors object is a boolean and not a number . 但是它始终在传递,即使我的错误对象是boolean而不是number What am I doing wrong? 我究竟做错了什么?

note: the logs look like this 注意:日志如下所示

this is error: false

在此处输入图片说明

You can check json schema using avj in Postman as follows: 您可以使用Postman中的avj检查json模式,如下所示:

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

Data: 数据:

{
    "errors": false
}

Result: Pass 结果:通过


Data: 数据:

{
    "errors": true
}

Result: Pass 结果:通过


Data: 数据:

{
    "errors": 123
}

Result: Fail 结果:失败


An alternate way 另一种方式

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

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

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