简体   繁体   English

如何检查一个值是否在 JSON 返回中?

[英]how do I check if a value is in a JSON return or not?

I'm writing a test in postman where I want to check if a JSON return contains the Label called 'RegressieMapTest'.我正在 postman 中编写一个测试,我想检查 JSON 返回是否包含名为“RegressieMapTest”的 Label。 This is my script:这是我的脚本:

pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj =  JSON.parse(objString);

for (var i = 0; i < obj.Corsa.Data.length; i++){
    if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
        console.log(obj.Corsa.Data[i].Label);
        pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
    }
}
pm.expect.fail();   
})

But it doesn't quite work, every time I run this script it seems like it automatically jumps to pm.expect.fail() which is weird because 'RegressieMapTest' is inside the JSON return.但它不太好用,每次我运行这个脚本时,它似乎会自动跳转到 pm.expect.fail(),这很奇怪,因为“RegressieMapTest”在 JSON 返回内。 Postman returns the following message: Postman 返回以下消息:

Is the folder created correctly? | AssertionError: expect.fail()

pm.respose.json() is equalent to JSON.parse you don't have to do it again pm.respose.json() 等于 JSON.parse 你不必再做一次

also you can use array.find method instead of looping through it你也可以使用 array.find 方法而不是循环遍历它

pm.test("Is the folder created correctly?", function () {
    var jsonData = pm.response.json();

    pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined

}

if array has any element with label RegressieMapTest then it will return that data elese returns undefined, so we are validating that it will not return undefined.如果数组有任何元素与 label RegressieMapTest 那么它将返回数据 elese 返回未定义,因此我们正在验证它不会返回未定义。 Meaning it has the value意味着它具有价值

Your pm.expect.fail();你的pm.expect.fail(); always runs.总是运行。 You want it to run only when you don't find the field.您希望它仅在找不到该字段时运行。 So just add a flag in your check block.因此,只需在您的检查块中添加一个标志。

pm.test("Is the folder created correctly?", function(){
    var jsonData = pm.response.json();
    var objString = JSON.stringify(jsonData);
    var obj =  JSON.parse(objString);

    var isFound = false;
    for (var i = 0; i < obj.Corsa.Data.length; i++){
        if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
            console.log(obj.Corsa.Data[i].Label);
            pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
            isFound = true;
        }
    }

    if (!isFound) {
        pm.expect.fail();
    }
})

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

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