How to filter response based on specific custom field?

Thanks, everyone.

When I get the response with this API https://reqres.in/api/users?page=2

I could see the response as below, but I would like to filter the data if email = “lindsay.ferguson@reqres.in”, could someone help here?

{
    "page": 2,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [
        {
            "id": 7,
            "email": "michael.lawson@reqres.in",
            "first_name": "Michael",
            "last_name": "Lawson",
            "avatar": 
        },
        {
            "id": 8,
            "email": "lindsay.ferguson@reqres.in",
            "first_name": "Lindsay",
            "last_name": "Ferguson",
            "avatar": 
        },
        {
            "id": 9,
            "email": "tobias.funke@reqres.in",
            "first_name": "Tobias",
            "last_name": "Funke",
            "avatar": 
        },
        {
            "id": 10,
            "email": "byron.fields@reqres.in",
            "first_name": "Byron",
            "last_name": "Fields",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
        },
        {
            "id": 11,
            "email": "george.edwards@reqres.in",
            "first_name": "George",
            "last_name": "Edwards",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
        },
        {
            "id": 12,
            "email": "rachel.howell@reqres.in",
            "first_name": "Rachel",
            "last_name": "Howell",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
        }
    ]
}

Hey @Venkat.batchu81

It doesn’t look like that endpoint offers the ability to filter down the response, some endpoints would offer that capability via URL params. It looks like they have this for some items like page but not much else.

Depending on your use case you can still do this in a couple of ways with Postman. In the Tests tab, you can loop through the objects in the data array and log the one that contains the email address to the console

_.each(pm.response.json().data, (item) => {
    if(item.email === 'lindsay.ferguson@reqres.in') {
        console.log(item)
    }
})

I’ve also created a template, which can be imported directly into your Postman app, that uses the jsonpath syntax in the Visualizer to filter down the response data.

This would be something that you could use to filter down to an object containing a specific email address:

$..data[?(@.email=='lindsay.ferguson@reqres.in')]

4 Likes

Thanks @danny-dainton , its working perfectly.

1 Like

Hi Danny,

I am working on something similar. I am very new to postman and I am not familiar with Javascript.

I am pulling the Etsy API on all active listings using a GET request: https://openapi.etsy.com/v2/listings/active

I want the listings that have views > 5000. How can I filter the results this way? Will I get the response in the Body?

Thank you

Have you tried any of the ways I mentioned?

Is there something that isn’t working for you?

You might need to expand on the information for anyone to help here. Not sure what the full response body is and where that particular views property is in the structure.

Hi Danny,

I am very new and learning postman so I am trying to understand the features.

I am learning how to use the Etsy API to get a list of all the active listings. However, there are over 50,100 active listings and I want the response to my GET request to spit out only listings with views > 5,000.

Views is not a parameter of the activelistings method but it is one of the properties (I am not sure if this the right terminology) of the response. I have attached the response. I am asking how I can filter so I can get a response that has only listings with views > 5,000

Thanks for your help.

How to do not empty the filled expression when switching the postman table page

Another problem is that it does not support retrieval of multiple fields, Like this expression, it works fine elsewhere, but not here

$..tasks[*]['id','uuid'] // TypeError: p is not a function
$..tasks[*]['id', 'uuid'] 
// Error: Lexical error on line 1. Unrecognized text.
// $..tasks[*]['id', 'uuid']
// -----------------^

That’s using the JSONpath CDN to do all the things so if any functionality is missing, it’s due to it not being in that external javascript code. :joy:

Have you looked at the script? Could you modify it or adapt it using a different source?

So which javascript source can I refer to to support this expression?

I don’t know but I also don’t know your use case. You’ve just jumped on a thread and said something doesn’t work without providing any context.

The collection I created was an example of how JSONpath could be used in the visualizer. It’s just a simple usecase to filter the response data using those queries.

The link added is old and static in the test script, perhaps newer versions have that functionality. Try updating it to a later version or use something else completely different in there and adapt that to your needs.

OK, I’ll append the structure I extracted

// json response
{
    "tasks": [
        {
            "id": "1",
            "t_type": "production",
            "t_uuid": "1e5c466c6b6e4539af5f47a3f5256352",
        },
       {
            "id": "2",
            "t_type": "development",
            "t_uuid": "1e5c466c6b6e4539af5f47a3f5256352",
        }
    ],
    "page": {
        "offset": 0,
        "limit": 100,
        "total": 1
    }
}

expression:

$..tasks[*]['id', 't_type']

Testing here is working fine.

// Extract results
[
   {
      "id" : "1",
      "t_type" : "production"
   },
   {
      "id" : "2",
      "t_type" : "development"
   }
]

Also, I updated jsonpath to version 1.1.1 and it still doesn’t work

There’s your answer, the functionality is not part of the JSONpath CDN or an updated version of the one that I was using in the example.

I can 100% not do anything about that :joy: - I have absolutely no idea what flavour of JSONpath that other it is using.

That’s a shame, I can’t find any other way :sob:

Hello @danny-dainton
Thankyou for these explanations and I also got the list of variables which equals to a name I have inserted. Now there are multiple values in the console log. What I need is to get the value one before the last one. But I can’t get it.

This is the usual response before filtering.

[
  {
  "carversion" : "nissan",
  "price" : "2345",
  "Id" : 70
  },
 {
  "carversion" : "bmw",
  "price" : "23w5",
  "Id" : 73
  },
{
  "carversion" : "benz",
  "price" : "23w5",
  "Id" : 74
  },
{
  "carversion" : "bmw",
  "price" : "23w5",
  "Id" : 78
  }
]

I tried following way!

_.each(pm.response.json().data, (item) => {
    if(item.carversion=== 'bmw') {
    var IdArray = item.Id;
   console.log(IdArray);

    }
})

This is what I get once I use above code. (all Ids of BMW cars are listed)

73
78
99
101

1.Now, what I need is to take the last value - 101
2. And I need to take one before the last value - 99

and set them both to the environment variables.

Could you please help? :slightly_frowning_face:

FWIW, I had a slight issue with the code as written by @danny-dainton originally. For some reason (and shoot me as I am no dev), pm.response.json().data results in undefined when logged into the console. So for me, I had to drop the .data property. I suspect this is how my response is returned, which seems to be an array of JSON, although it is similar to @technical-operator-7 JSON, so I’m not sure.

Anyhow, this did it for me:

_.each(pm.response.json(), (item) => {
    if (item.policyId === 'POuOxVNZOjRANT8QlocjvCJg2') {
        console.log(item);
    }
})

Where the JSON was:

[
    {
        "projectId": "PR6OEZ...smEMGwIgZiw2",
        "teamId": null,
        "policyId": "PO4aVENVH1bMGwi7YL5LtHFA2",
        "blueprintId": "BPduy...0BMWZI4g2",
        "description": null,
        "status": "Suspended",
        "externalCloudData": null,
        "ownerEmail": "me@example.com",
        "regionId": "REKolD1...ODeMGob9A2",
        "name": "Demo-VPN-Shared-Env",
        "id": "ENkgiWyq...asDb_3O6OyA2"
    },
    {
        "projectId": "PR6OEZ...smEMGwIgZiw2",
        "teamId": null,
        "policyId": "POxw3PYqFVKEps11REEgteiQ2",
        "blueprintId": "BPwwS..YVoMvXaA2",
        "description": "<p>\r\n\tESXi 7.0.1&nbsp;<span style=\"font-size:12px\">Env with Extrahop VMs</span></p>",
        "status": "Suspended",
        "externalCloudData": null,
        "ownerEmail": "me@example.com",
        "regionId": "REKol...xODeMGob9A2",
        "name": "Lab201",
        "id": "ENrX5DaE..yVUNDyQ2"
    },
    {
        "projectId": "PR6OEZ...smEMGwIgZiw2",
        "teamId": null,
        "policyId": "POuOxVNZOjRANT8QlocjvCJg2",
        "blueprintId": "BPIagd...m67Cn2GbNjA2",
        "description": "",
        "status": "Ready",
        "externalCloudData": null,
        "ownerEmail": "me@example.com",
        "regionId": "RE6OEZs-y-mkK1mEMGwIgZiw2",
        "name": "No VMs in Amsterdam",
        "id": "ENUI4z1...U1agsi327rjA2"
    },
    {
        "projectId": "PR6OEZ...smEMGwIgZiw2",
        "teamId": null,
        "policyId": "POuOxVNZOjRANT8QlocjvCJg2",
        "blueprintId": "BPgVKL2Y...InqAPmqlQA2",
        "description": "",
        "status": "Ready",
        "externalCloudData": null,
        "ownerEmail": "me@example.com",
        "regionId": "REKolD1...ODeMGob9A2",
        "name": "No VMs in Miami",
        "id": "ENdOu...1VaOhiAqCLv99Q2"
    },
    {
        "projectId": "PR6OEZ...smEMGwIgZiw2",
        "teamId": null,
        "policyId": "POm9lJpTlFn0sih_OctX1u6g2",
        "blueprintId": "BPdg...4RnM7ku9r3f6Q2",
        "description": "",
        "status": "Suspended",
        "externalCloudData": null,
        "ownerEmail": "me@example.com",
        "regionId": "REKolD1-...DeMGob9A2",
        "name": "Windows Boxes",
        "id": "ENYK_...uZW02Wgqjg2"
    }
]

Which returns the two items I wanted:

{projectId: "PR6OE...mEMGwIgZiw2", teamId: null, policyId: "POuOxVNZOjRANT8QlocjvCJg2"…}
 
{projectId: "PR6OE...mEMGwIgZiw2", teamId: null, policyId: "POuOxVNZOjRANT8QlocjvCJg2"…}

On a side note, for the first time, I used the Postbox AI to write a test to “Filter JSON based on a specific field”, and this is what I got:

pm.test("Filter JSON based on a specific field", function () {
    var responseData = pm.response.json();

    responseData.forEach(function (item) {
        if (item.policyId === 'POuOxVNZOjRANT8QlocjvCJg2') {
            pm.expect(item).to.have.property('id');
            pm.expect(item).to.have.property('name');
        }
    });
});

Which is amazing!

1 Like

@swinster

Or you can use the JavaScript filter or find functions (negating the need for the forEach loop).

Find if you expect only one result, or filter if it might return more than one result.

let search = responseData.find(function (item) {
    return item.policyId === 'POuOxVNZOjRANT8QlocjvCJg2';
});

AI will be after all of our jobs soon :slight_smile:

1 Like

My original syntax was for a different response payload so it’s only really going to work with something of the same structure.

Glad to see you got something working! :trophy: