首页 > 解决方案 > 如何使用 ajv 模式验证验证值是否为格式和/或类型为 double?

问题描述

我使用的是 Ajv 版本 07。

我正在尝试使用 ajv 验证来验证 JSON 响应正文返回的属性的值在邮递员中的类型和格式为 double,但是,我无法做到这一点。我试过在网上搜索它,但仍然没有找到任何关于它的信息。

我试过输入以下内容:

上述所有尝试均不成功,因为它们都带有一条错误消息:

或者

有人能帮我解决这个问题吗?

图式

var Ajv = require ('ajv'),
ajv = new Ajv ({logger:console}),
expectedResponseSchema = 
{
    "items": {
        "required": [
            "payments"
     ],
        "properties": {
    "payments": {
                "items": {
                    "required": [
                        "amount"
    ]
        "properties": {
                        "amount": {
                            "$id": "#/items/properties/payments/items/properties/amount",
                            "type": "number",
                            "format": "double"
                        }
   }
  }
 }
}
}

邮递员测试

var currentSchPmExpTest;

try{     
currentSchPmExpTest = ' expectedResponseSchema variable';
    pm.expect(ajv.validate(expectedResponseSchema, jsonData)).to.be.true;
pm.test('Test 1 - PASSED - expectedResponseSchema variable data matches schema returned by body response!', () => true);
} catch(e){
    pm.test('Test 1 - FAILED - Expected data does not match response body data!', () => {throw new Error(e.message + " in " + currentSchPmExpTest)});
}

身体反应


[
  {
    "payments": [
      {
        "amount": 2.200000045367898,

      }
    ]
  }
]

标签: javascriptpostmanjson-schema-validatorajv

解决方案


我不确定您从哪里获得类型和格式,但根据AJV 文档(可能已过时),这不是有效的type.

在此处输入图像描述

编辑:

从您的更新中,我建议将测试脚本更改为类似这样的内容,以便检查您正确的部分架构:

let schema = {
    "type": "array",
    "items": {
        "type": "object",
        "required": [
            "payments"
        ],
        "properties": {
            "payments": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": [
                        "amount"
                    ],
                    "properties": {
                        "amount": {
                            "type": "number",
                        }
                    }
                }
            }
        }
    }
}

pm.test("Check Schema", () => {
    pm.response.to.have.jsonSchema(schema)
}) 

如果您也需要,try/catch可以在此周围添加块。


推荐阅读