Search for a specific value in JSON

My question:
I’m trying to check response body if there’s a user which has last_name = “Holt” in following JSON file. with writing a test script in Postman

I’ve already tried:

pm.test("Last Name Holt", function () {
    var jsonData = JSON.parse(responseBody);
    value = pm.expect(jsonData[0].last_name).to.eql("Holt");
});

and

pm.test("Last Name Holt", function () {
    const responseJson = pm.response.json();
    pm.expect(responseJson.data[3].last_name).to.eql("Holt");
});

2nd code piece returns true but that’s directly looking into data[3] I want to search amongst all last_names in the file.

1 Like

Hi @supply-meteorologis4

Try using a for loop… something like this;

const jsonData = pm.response.json();

pm.test("Check last Name Holt exists.", function () {
    for (let i = 0; i < jsonData.data.length; i++) {
        if(jsonData.data[i].last_name === "Holt"){
            console.log("The last name Holt exists.")
        }else{
            console.log("The last name Holt not found.")
        };
    }
});
1 Like

Hey @w4dd325

I tried this one:

pm.test("Last Name Holt", function () {
  const responseJson = pm.response.json();
  pm.expect(responseJson.data.some(o => o.last_name == 'Holt')).to.be.true;
});

But yours as well looks like a thing to get the job done. Thank you!

1 Like

You could also use “find”.

const jsonData = pm.response.json();

pm.test("Check last Name Holt exists.", () => {
    let result = jsonData.data.find(a => a.last_name === "Holt")
    console.log(result);
    pm.expect(result.last_name).to.eql("Holt")
});
1 Like

Also, if it helps…

If you were looking for multiple matches, you could use “filter”… It finds all the matches and stores them in a new array, so you would have to reference the array index you wanted to assert;

const jsonData = pm.response.json();
pm.test("Check last Name Holt exists.", () => {
    let result = jsonData.data.filter(a => a.last_name === "Holt")
    console.log("Number of matches = " + result.length)
    console.log(result);
    
    //(note the [0] for array index)
    pm.expect(result[0].last_name).to.eql("Holt")

});
1 Like