I am using Javascript’s JSON.stringify()
function to convert a list of strings into a comma separated JSON object.
array = ["a", "b", "c"];
console.log(JSON.stringify(array));
// Output: ["a","b","c"]
I want to add a single space between list elements. I attempted to use the space
parameter, but this added extra newlines to my output.
array = ["a", "b", "c"];
console.log(JSON.stringify(array, null, " "));
// Desired output:
// ["a", "b", "c"]
//
// Actual output:
// [
// "a",
// "b",
// "c"
// ]
There is a similar question about adding spaces between objects with JSON.stringify. However, the top answer recommends splitting elements by curly brackets and rejoining, whereas list elements are not separated by curly brackets.
How can I output JSON list elements separated by with a space when using JSON.stringify
?
3
Answers
Since list items are separated by a comma, it seems that replacing commas with a comma and a space should do the trick:
var myJSON = JSON.stringify(array).replaceAll(',', ', ');
Similar to @mykaf’s answer, but will not change string contents containing commas due to character escaping.
Just know that this only matters while your array is stringified. As soon as you deserialize back to an object, there are no commas in between elements, as that concept exists only in strings, not JSON objects/arrays.
You can use
replace
to remove the new line.