This may not be what you want, but if you just want it to look better, I would recommend:

console.log(JSON.stringify(products, null, 2));

which would give you

[
  {
    "name": "Sample Product Name"
  },
  {
    "name": "Sample Product Name 2"
  }
]

In the console. If you really just want a space before commas, you could do:

console.log(JSON.stringify(products).split('},{').join('}, {'));

http://jsfiddle.net/2MeMY/3/

Answer from dave on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript | MDN
If it is a string, successive levels will be indented by this string. Each level of indentation will never be longer than 10. Number values of space are clamped to 10, and string values are truncated to 10 characters. ... JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' ...
Top answer
1 of 4
42

This may not be what you want, but if you just want it to look better, I would recommend:

console.log(JSON.stringify(products, null, 2));

which would give you

[
  {
    "name": "Sample Product Name"
  },
  {
    "name": "Sample Product Name 2"
  }
]

In the console. If you really just want a space before commas, you could do:

console.log(JSON.stringify(products).split('},{').join('}, {'));

http://jsfiddle.net/2MeMY/3/

2 of 4
3

If you want a json-output that is:

  1. Single-line
  2. Has spaces between prop-names and prop-values (and between items)
  3. Has spaces between each comma and the next prop-name/item

You can use this:

function Stringify_WithSpaces(obj) {
	let result = JSON.stringify(obj, null, 1); // stringify, with line-breaks and indents
	result = result.replace(/^ +/gm, " "); // remove all but the first space for each line
	result = result.replace(/\n/g, ""); // remove line-breaks
	result = result.replace(/{ /g, "{").replace(/ }/g, "}"); // remove spaces between object-braces and first/last props
	result = result.replace(/\[ /g, "[").replace(/ \]/g, "]"); // remove spaces between array-brackets and first/last items
	return result;
}

let obj = [{name: "Sample Product Name"}, {name: "Sample Product Name 2"}];
console.log("Stringified with spaces: " + Stringify_WithSpaces(obj));

And here's the function as a one-line expression:

JSON.stringify(obj, null, 1).replace(/^ +/gm, " ").replace(/\n/g, "").replace(/{ /g, "{").replace(/ }/g, "}").replace(/\[ /g, "[").replace(/ \]/g, "]")

Extended Typescript version


Here's a more verbose version (in Typescript) with options:

export class ToJSON_WithSpaces_Options {
    insideObjectBraces = false;
    insideArrayBrackets = false;
    betweenPropsOrItems = true;
    betweenPropNameAndValue = true;
}
export function ToJSON_WithSpaces(obj, options?: Partial<ToJSON_WithSpaces_Options>) {
    options = Object.assign({}, new ToJSON_WithSpaces_Options(), options);

    let result = JSON.stringify(obj, null, 1); // stringify, with line-breaks and indents
    result = result.replace(/^ +/gm, " "); // remove all but the first space for each line
    result = result.replace(/\n/g, ""); // remove line-breaks
    if (!options.insideObjectBraces) result = result.replace(/{ /g, "{").replace(/ }/g, "}");
    if (!options.insideArrayBrackets) result = result.replace(/\[ /g, "[").replace(/ \]/g, "]");
    if (!options.betweenPropsOrItems) result = result.replace(/, /g, ",");
    if (!options.betweenPropNameAndValue) result = result.replace(/": /g, `":`);
    return result;
}

Ideally, this sort of function will apply the regular-expressions prior to removing the line-breaks (so that it can guarantee it's not modifying text within user-supplied strings), but I'll leave that for someone else to do since the above is sufficient for my use-case (and I think most others).

🌐
Futurestud.io
futurestud.io › tutorials › node-js-human-readable-json-stringify-with-spaces-and-line-breaks
Node.js — Human-Readable JSON.stringify() With Spaces and Line Breaks
Serializing JavaScript to JSON is useful in various situations. Calling JSON.stringify(data) returns a JSON string of the given data. This JSON string doesn’t include any spaces or line breaks by default. It’s hard to read when writing the serialized JSON to a file.
🌐
W3Schools
w3schools.com › jsref › jsref_stringify.asp
JavaScript JSON stringify() Method
/*Insert the word SPACE for each white space:*/ var obj = { "name":"John", "age":"39", "city":"New York"}; var text = JSON.stringify(obj, null, "SPACE"); Try it Yourself »
🌐
The Code Barbarian
thecodebarbarian.com › the-80-20-guide-to-json-stringify-in-javascript
The 80/20 Guide to JSON.stringify in JavaScript | www.thecodebarbarian.com
JSON.stringify(obj, null, 2); The spaces string doesn't have to be all whitespace, although in practice it usually will be.
🌐
DhiWise
dhiwise.com › post › javascript-essentials-detailed-exploration-of-json-stringify
Exploring JSON Stringify: An In-Depth Exploration
September 29, 2023 - JSON Stringify's space option is used to inject white space into the output JSON string for readability.
🌐
Rip Tutorial
riptutorial.com › stringify with white-space
JSON Tutorial => Stringify with white-space
var JSONObject = { stringProp: 'stringProp', booleanProp: false, intProp: 8 } var JSONString = JSON.stringify(JSONObject, null, 2); console.log(JSONString); /* output: * { * "stringProp": "stringProp", * "booleanProp": false, * "intProp": 8 * } */
🌐
Medium
medium.com › @mujaffarhssn › are-you-familiar-with-the-hidden-powers-of-json-stringify-function-59e230accd99
Are You Familiar with the Hidden Powers of JSON.stringify() Function? | by TechInsights | Medium
November 4, 2023 - Here, the space argument is set to the string '--', causing the JSON string to be indented with double dashes. Now that you have a comprehensive understanding of JSON.stringify(), you can leverage this knowledge to optimize your data serialization ...
Find elsewhere
🌐
Tabnine
tabnine.com › home › how to use json.stringify
How to use JSON.stringify - Tabnine
July 25, 2024 - JSON.stringify(object, replacer, ... properties to convert to JSON · Space – optional – a formatting helper to insert a number of spaces between each JSON element....
🌐
DEV Community
dev.to › iammtander › jsonstringify-javascript-serialization-simplified-5akf
JSON.stringify: JavaScript Serialization Simplified - DEV Community
February 10, 2024 - value: The value to convert to a JSON string. replacer: An optional parameter that can be a function or an array used to modify the output JSON. space: An optional parameter that specifies the indentation of nested structures.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
JSON methods, toJSON
The third argument of JSON.stringify(value, replacer, space) is the number of spaces to use for pretty formatting.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 49766
JSON.stringify space (third) argument should allow nulls · Issue #49766 · microsoft/TypeScript
May 2, 2022 - JSON.stringify() at MDN: States it should be a Number, String or the value null (or omitted). stringify(value [, replacer [, space]]) in the spec: Is even more lenient as it states
Published   Jul 02, 2022
🌐
SamanthaMing
samanthaming.com › tidbits › 45-pretty-json-output
Pretty JSON Output | SamanthaMing.com
const protein = { steak: '🥩', bacon: '🥓' }; JSON.stringify(protein); // {"steak":"🥩","bacon":"🥓"} JSON.stringify(protein, null, 2); /* { "steak": "🥩", "bacon": "🥓" } */ Tab Spacing 😉 · Understanding the "Space" argument · a. Number · b.
🌐
Scaler
scaler.com › home › topics › javascript json stringify() method
JavaScript JSON stringify() Method - Scaler Topics
May 4, 2023 - Replacer: an array or function which signifies changes to the resultant string. Space: a number or string which specifies the number and type of space to be included in between keys.
🌐
DEV Community
dev.to › oliverjumpertz › indenting-json-stringify-s-output-5gfd
Indenting JSON.stringify’s Output - DEV Community
November 3, 2022 - You could add an indentation of two white spaces like so: const obj = { propertyOne: 1, propertyTwo: “2”, propertyThree: { nestedPropertyOne: 1.123 } }; // Using 2 is basically the same as using “ “. console.log(JSON.stringify(obj, null, 2)); // prints => // { // "propertyOne": 1, // "propertyTwo": "2", // "propertyThree": { // "nestedPropertyOne": 1.123 // } // }
🌐
W3Resource
w3resource.com › JSON › snippets › json-stringify-pretty.php
JSON.stringify for Pretty Print
JSON.stringify is a method in JavaScript that converts a JavaScript object into a JSON string. By default, the output of JSON.stringify is a compact string without extra spaces or line breaks.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-json-stringify-method
JavaScript JSON stringify() Method | GeeksforGeeks
March 14, 2024 - It can be a number or a string if it is a number then the specified number of spaces are indented to the final string and if it is a string then that string is (up to 10 characters) used for indentation.
🌐
Rocketsoftware
m204wiki.rocketsoftware.com › index.php › Stringify_(Json_function)
Stringify (Json function) - m204wiki
This will make the serialized JSON data much nicer and easier to read. The Indent value indicates the number of blank characters per indentation level to place before each new line of data. Every array and object increases the indentation level by one inside its boundaries. So if an array is inside an object which is inside another object, that array's indentation level is 3. With an Indent value of 2, each array item in that array will have 6 space characters in front of it.