Today I learned: How to log a JavaScript object with indentation to the console
Posted on
Use JSON.stringify() function
Although I was using the JSON.stringify() function for years; I found myself
logging JavaScript objects to the console the most unproductive way.
Worse, upon need, I would copy paste the output into a JSON formatter.
Efficiently use JSON.stringify() function
I discovered today that the JSON.stringify() function takes two additional
arguments: replacer and space.
I will leave out the replacer argument of this post, but the space argument
is all I ever needed.
As stated in MDN:
The
spaceargument may be used to control spacing in the final string.If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10).
If it is a string, successive levels will be indented by this string (or the first ten characters of it).
This means that:
- JSON.stringify({ a: 2 }, null, ' ');will indent by 1 space
- JSON.stringify({ a: 2 }, null, 1);will also indent by 1 space
- JSON.stringify({ a: 2 }, null, 4);will also indent by 4 spaces
- JSON.stringify({ a: 2 }, null, 15);will indent by 10 spaces
- JSON.stringify({ a: 2 }, null,\t- );will indent with tabs
Example: Output indented with tabs
Below your can find the example taken from MDN for indenting with tabs:
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'