Capitalize the first letter of each json response key in Postman Tests

My question: How do I capitalize the first letter of each json response key in Postman Tests?

Details (like screenshots): I tried experimenting with some answers here and on StackOverflow already and my current attempt looks like this

const jsonData = pm.response.json();

for(var key in jsonData){
return key.charAt(0).toUpperCase() + key.slice(1);
}

console.log(jsonData);

How I found the problem:

The response body in the console still shows this

{
“abc”: “N”,
“quoteNum”: null,
“blahCreated”: “N”,
“insId”: null,
“quoteNum2”: null
}
when I want it to look like

{
“Abc”: “N”,
“QuoteNum”: null,
“BlahCreated”: “N”,
“InsId”: null,
“QuoteNum2”: null
}

First comment I would like to make is that you have set jsonData as a constant.

Therefore, you can’t change the info in it. It’s read only.

Change the variable type to something you can update.

Thanks for your idea MD. I first tried replacing const with let, then let with var and saw the same response body in the Console tab at the bottom left of the desktop.

Then I added

console.log(“Hey”);

and didn’t see Hey in the console

You’re missing the semicolon on the previous line to separate the statements.

What do you mean by previous line? In my screenshot from around 40 minutes ago, I checked to make sure I had all the semicolons to end statements.

No console text is printed likely because the return in your for loop terminates the test script.

Thank you, I now see the console logs and I see that the logic I built for capitalizing the first letter of keys isn’t working. Do you see what I might try instead?

@bencook16

The following seems to work…

// const jsonData = pm.response.json();

var jsonData = {
"abc": "N",
"quoteNum": null,
"blahCreated": "N",
"insId": null,
"quoteNum2": null
};

console.log("before...............................");
console.log(jsonData); 

for(var key in jsonData){
 delete Object.assign(jsonData, {[key.charAt(0).toUpperCase() + key.slice(1)]: jsonData[key] })[key];
}

console.log("after...............................");
console.log(jsonData); 

image

1 Like

That worked, thank you Mike!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.