Home > Mobile >  How do I add spaces between list elements when using JSON.stringify?
How do I add spaces between list elements when using JSON.stringify?

Time:01-18

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?

CodePudding user response:

Similar to @mykaf's answer, but will not change string contents containing commas due to character escaping.

const array = ["string without commas", "string,with,commas"];
const myJSON = JSON.stringify(array).replaceAll(',"', ', "');
// '["string without commas", "string,with,commas"]'

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.

CodePudding user response:

You can use replace to remove the new line.

array = ["a", "b", "c"];
console.log(JSON.stringify(array, null, 1).replace(/\n/g, ''));

CodePudding user response:

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(',', ', ');

  • Related