JSON.stringify添加回车



我正在使用poster进行批量API调用,并希望在每个记录之间有一条新行(为了方便其他人复制并粘贴到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));

我试过

JSON.stringify(responses, '},', '},n')

不起作用

这就是输出的样子{"成功":真,"数据":"0.5950391865600001\t0.49508964727322147\t193383783","id":"2ec0a50f-862e-11ec-a41f-06c185e97372"},{"成功":真,"数据":"0.5950391865600001\t0.49508964727322147","id":"410113f9-8630-11ec-a41f-06c185e97372"},

最简单、最可靠的方法是将每个数组元素单独字符串化,而不是全部字符串化:

const json = theArray.map(el => JSON.stringify(el)).join(",n");

实例:

const theArray = [
{id: 1},
{id: 2,},
{id: 3},
];
const json = theArray.map(el => JSON.stringify(el)).join(",n");
console.log(json);

我在那里省略了[],因为你似乎不想要它们,但你当然可以添加它们("["+array.map(//(+"\n]"(。

尽管JSON.stringify接受第三个可以用于缩进的参数(这会触发漂亮的打印(,但将其用于此目的是不明智的。可以提供一个空格,然后替换"n ",因为JSON值中不会出现文本换行符:

const json = JSON.stringify([1, 2, 3], null, 1)
.replace(/n /g, "n");
console.log(json);

但它有点古怪。

最新更新