最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to compare two JSON objects excluding the fields that are specified in a separate array?(Postman Script) - Stac

programmeradmin1浏览0评论

I have two JSON object one is input and other is output, I wanna verify whether the output is same as input that I have specified in input along with key and value, also it should not pare for fields that I have specified in a 'exclude' array.

Json Object1:(input)
{
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "createdCanvasAgentId": 2,
    "isActive": 1
}
Json Object2:(output)
{
    "id": 53,
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "qty": null,
    "createdCanvasAgentId": 2,
    "isActive": true
}

Fields I should neglect while paring is in 'exclude' array

exclude = {"id","qty","isActive"}

Code Snippet is as follows:

//Input 
var en_val = pm.environment.get("my_array");
console.log(en_val);

keysave = Object.keys(JSON.parse(en_val));
console.log(keysave);

valuesave=Object.values(JSON.parse(en_val));
console.log(valuesave);

// Output
var resdata = JSON.parse(responseBody);
console.log(resdata);

keylist = Object.keys(resdata.data.list[0]);
console.log(keylist);

valuelist =Object.values(resdata.data.list[0]);
console.log(valuelist);

// exclude contains array of values that need not be pared
var ex=pm.environment.get("exclude");
var excludeKeys = Object.keys(JSON.parse(ex));

I have two JSON object one is input and other is output, I wanna verify whether the output is same as input that I have specified in input along with key and value, also it should not pare for fields that I have specified in a 'exclude' array.

Json Object1:(input)
{
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "createdCanvasAgentId": 2,
    "isActive": 1
}
Json Object2:(output)
{
    "id": 53,
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "qty": null,
    "createdCanvasAgentId": 2,
    "isActive": true
}

Fields I should neglect while paring is in 'exclude' array

exclude = {"id","qty","isActive"}

Code Snippet is as follows:

//Input 
var en_val = pm.environment.get("my_array");
console.log(en_val);

keysave = Object.keys(JSON.parse(en_val));
console.log(keysave);

valuesave=Object.values(JSON.parse(en_val));
console.log(valuesave);

// Output
var resdata = JSON.parse(responseBody);
console.log(resdata);

keylist = Object.keys(resdata.data.list[0]);
console.log(keylist);

valuelist =Object.values(resdata.data.list[0]);
console.log(valuelist);

// exclude contains array of values that need not be pared
var ex=pm.environment.get("exclude");
var excludeKeys = Object.keys(JSON.parse(ex));
Share Improve this question asked Oct 31, 2018 at 6:19 Raji BaskarRaji Baskar 1111 gold badge2 silver badges11 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2
Json Object 1: keysave,valuesave
Json Object 2: keylist,valuelist
//values that aren't need to be checked
exclude = ["id","qty","isActive"]

Code:

 var ex1=pm.environment.get("exclude");
    var resp=[];
    for (var i in keysave)
     {    
        console.log(keysave[i]);    
        if(ex1.indexOf(keysave[i]) < 0)   
        {           
            var flag =0;        
            for (var j in keylist) 
            {       
                if(keylist[j] === keysave[i] && valuelist[j] === valuesave[i])
                {           
                    flag = 0;           
                    break;      
                }       
                else 
                {                       
                    flag = 1;

                }   
            }           
            if(flag === 0)
            {       
                console.log("Matched value "+keysave[i]);   
            }   
            else 
            {       
                console.log("None matched value "+keysave[i]);  
                resp.push(keysave[i])       
                console.log(resp);  
            }       
        }
    }
    if(resp.length > 0)
    {    
        tests[resp] = false;
    }
    else
    {    
        tests['Both JSON are Equal'] = true;
    }

You can take advantage of the second argument in JSON.parse(text, reviver)

reviver - If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Also, you should take advantage of integrated lodash helpers.

Here is a plete example of a Test in Postman

const original = {
    city: 'New York'
}

const json = '{"id":10,"city":"New York","qty":5}'
const exclude = ['id', 'qty']
const reviverFilter = (k, v) => exclude.includes(k) ? undefined : v
const expected = JSON.parse(json, reviverFilter)

pm.test('Equals', function() {
    pm.expect(_.isEqual(original, expected)).to.be.true
});

Maybe you can use _.isEqual method from lodash?

This _.isEqual method will return true when both are same. And for the excluding part, I believe you can pass a function as a third parameter during a call, which that function will do the checking to neglect the property that you want to ignore. And I suggest you to use _.includes to handle the checking inside the function. Hope that helps..

Thanks.

[https://lodash./docs/4.17.10#isEqual] [https://lodash./docs/4.17.10#includes]

Custom implementation of pare two objects with keys to exclude.

var b = {
    "id": 51,
    "name": "Sonsssu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "qty": null,
    "createdCanvasAgentId": 2,
    "isActive": true
};
var a = {
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "createdCanvasAgentId": 2,
    "isActive": 1
};
var exclude = ["id","qty","isActive"];

function pareObject(first, second,excludeKeys) {
    var excludes = {};
    var isSame = true;
    if(excludeKeys) {
        excludeKeys.forEach(function (key) {
            if (!excludes.hasOwnProperty(key)) {
                excludes[key] = 1;
            }
        });
    }
    Object.keys(first).forEach(function (key) {
        if(!excludes.hasOwnProperty(key)){
            if(first[key] !== second[key]){
                isSame = false;
            }
        }
    });
    return isSame;
}

console.log(pareObject(a,b.exclude));

You should write a function to convert original objects to temporary objects, then pare them.

function convertToObjectWithExcludeKeys(orginalObject, excludeKeys){
    var newObj = {};
    Object.keys(orginalObject).map(key => {
      if(excludeKeys.indexOf(key) < 0){
        newObj[key] = orginalObject[key];  
      }

    })
    return newObj;
}


var b = {
    "id": 51,
    "name": "Sonsssu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "qty": null,
    "createdCanvasAgentId": 2,
    "isActive": true
};
var a = {
    "name": "Sonu",
    "city": "NewYork",
    "Amount": 5000,
    "mode": "Weekly",
    "duration": "15",
    "createdCanvasAgentId": 2,
    "isActive": 1
};

var excludeKeys = ["id","qty","isActive"];

//Convert original objects to temporary objects with exclude keys
var tmpA = convertToObjectWithExcludeKeys(a, excludeKeys);
var tmpB = convertToObjectWithExcludeKeys(b, excludeKeys);

console.log("tmpA", tmpA);
console.log("tmpB", tmpB);

//Then pare them .....

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论