JSON字符串化每行一个对象



是否可以将以下内容字符串化为预期的输出?

输入:

let output = JSON.stringify([
{
"Color": "Red", 
"Type":"Fast"
},
{
"Color": "Blue", 
"Type":"Slow"
}
]);

预期输出:

[
{"Color": "Red", "Type":"Fast"},
{"Color": "Blue", "Type":"Slow"}
]

您可以尝试逐个映射每个条目并进行字符串化,然后通过换行符将它们连接在一起:

const arr = [
{"Color": "Red", "Type":"Fast"},
{"Color": "Blue", "Type":"Slow"}
];
const result = "[n" + arr.map(e => '  ' + JSON.stringify(e)).join(',n') + "n]";
console.log(result)

相关内容

最新更新