skip to Main Content

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


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You can use replace to remove the new line.

    array = ["a", "b", "c"];
    console.log(JSON.stringify(array, null, 1).replace(/n/g, ''));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search