Search code examples
javascriptjsonpostmanpostman-testcase

Postman - Get response value using variable key


I've created a GET request in Postman that returns some data in a JSON format. I want to get the JSON response value for every key that contains a specific substring.

This is the code I've been trying:

var jsonData = pm.response.json();
var keys = Object.keys(jsonData);

for(var i = 0; i < keys.length; i++) 
{
    if(keys[i].has("_number"))
    { 
       console.log(jsonData.keys[i]);
    }
}

Edit: The issue isn't with the substring recognition, but with the return of the values. If I try to get a value using a specific key in the condition (e.g. jsonData.Id) it works just fine. It just doesn't work when I'm trying to use a variable.


Solution

  • You can check this way

    var jsonData = pm.response.json();
    var keys = Object.keys(jsonData);
    
    for(var i = 0; i < keys.length; i++) 
    {
        if(keys[i].includes('_number'))
        { 
           console.log(jsonData[keys[i]]);
        }
    }