Loop to test response body

Hello,

Below is a problem which looks simple with another language (ie. JAVA), but which I cannot reproduce in postman, and i need help. Ready? :slight_smile:

In this example, my response body is :

{
	"q1":{
		"label":"10%"
	},
	"q2":{
		"label":"20%"
	},

	...

	"q9":{
		"label":"90%"
	}
}

I would like to know if the label of each “q” has the great value.
I could just do :

var jsonData = pm.response.json();

pm.test("Check quantile label", function () {

    pm.expect(jsonData.q1.label).to.equal("10%");
    pm.expect(jsonData.q2.label).to.equal("20%");
    ...
    pm.expect(jsonData.q9.label).to.equal("90%");

});

But it will quickly become ugly if I have a lot more values to test…

The question is: why not like in java, use a loop to avoid code duplication and make it more generic? For example, the code below (which obviously does not work) :

var jsonData = pm.response.json();

pm.test("Check quantile label", function () {
	
	var quantileTab = ["10%", "20%", ..., "90%"];

	for(var i=1 ; i<=quantileTab.length ; i++){

	var currentQuantile = "q"+i;
	var currentValue = quantileTab[i-1];

    pm.expect(jsonData.currentQuantile.label).to.equal(currentValue);

});

The problem here is the last line of code, and more specifically “jsonData.currentQuantile.label”.
I have the impression that it is not possible to use variable like “currentQuantile” with jsonData, which must have ‘hard’ data.
Also, jsonData is an object, and giving a string like “currentQuantile” can be a problem.

I have been stuck on this problem for some time, without finding any answers, either on the forum or on the net. I tested a lot of things, but nothing. Do you have any idea or lead to help me please? Is my request possible under postman? :slight_smile:

Thank you all and have a nice day !

NL

You can iterate over a json objects keys, which should do what you want.

In your code snippet, you are treating the object like it’s an array, which is why your solution won’t work.

If you look at this answer on stack overflow, you can see how to quickly iterate over the keys.

Given your code snippet from above, you can easily modify the snippets in that stack overflow article to do what you want.

Everything works thanks to you and the link you sent me.
Thank you, really.

Have a nice day !

Nolan

1 Like

Happy to help! Good luck with everything :slight_smile: