'JSON.stringify add a carriage return
I am using postman for batch API calls and want a new line between each records (for the ease of others copy and pasting into csv/excel)
let responses = pm.collectionVariables.get('collectionResponses')
if(responses) {
responses = JSON.parse(responses);
} else {
responses = []
}
responses.push(pm.response.json());
pm.collectionVariables.set('collectionResponses', JSON.stringify(responses));
I tried
JSON.stringify(responses, '},', '},\n')
and that did not work
This is what the output looks like {"success":true,"data":"0.5950391865600001\t0.49508964727322147\t193.383783","id":"2ec0a50f-862e-11ec-a41f-06c185e97372"}, {"success":true,"data":"0.5950391865600001\t0.49508964727322147","id":"410113f9-8630-11ec-a41f-06c185e97372"},
Solution 1:[1]
The simplest, most reliable way of doing this is to stringify each array element individually rather than all together:
const json = theArray.map(el => JSON.stringify(el)).join(",\n");
Live Example:
const theArray = [
{id: 1},
{id: 2,},
{id: 3},
];
const json = theArray.map(el => JSON.stringify(el)).join(",\n");
console.log(json);
I've left off the [] there because you seemed not to want them, but of course you could add them (`"[" + theArray.map(/.../) + "\n]").
Although JSON.stringify accepts a third parameter you can use for indentation (which triggers pretty-printing), it's awkard to use it for this purpose. You could provide a single space and then replace "\n " since a literal newline won't appear within a JSON value:
const json = JSON.stringify([1, 2, 3], null, 1)
.replace(/\n /g, "\n");
console.log(json);
...but it's a bit hacky.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
