0

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.

MADi
  • 23
  • 8
  • What's the response body? – Danny Dainton Apr 21 '20 at 12:03
  • I don't know if it makes any difference but I'm using Runner to run the request. The response I'm getting is something like this ` { "Id": 12345, "name": "test", "date": "2020-05-20", "f1_number" : "1", "f2_number" : "2", "a1_number" : "1", "a2_number" : "2", . . . } ` – MADi Apr 21 '20 at 12:14
  • Hi i have edited my answer, hope that will help you, issue is here `console.log(jsonData[keys[i]])` – Narendra Chouhan Apr 21 '20 at 12:27
  • Thank you! That solves the issue. – MADi Apr 21 '20 at 12:52

3 Answers3

0

has() is only searching for an exact key within a map. Try this for checking a substring:

if(keys[i].indexOf("_number") !== -1)
{ 
   console.log(jsonData.keys[i]);
}

or even the string function includes()

if(keys[i].includes("_number"))
{ 
   console.log(jsonData.keys[i]);
}
Sebastian
  • 11
  • 2
  • The issue doesn't seem to be with the substring check. I tried your suggestions just to make sure but the values are still not returning. 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. – MADi Apr 21 '20 at 11:56
0

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]]);
    }
}
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24
0

Slightly different method but this would give the same output in the Postman Console:

_.each(Object.entries(jsonData), (item) => {
    if(item[0].includes('_number')) {
        console.log(item[1])
    }
})
Danny Dainton
  • 23,069
  • 6
  • 67
  • 80