This page looks best with JavaScript enabled

Why use JSON.stringify() in debugging statements?

 ·   ·  ☕ 2 min read

Does JSON.stringify() have anything to do in debugging statements today?

There were many Javascript-like systems that did not have the same tooling or debugging methods. I do not quite remember having browsers or ‘node’ print out the entire object back in the day - I may be wrong.

So it was that I had to use console quite a bit, and what better way to print objects other than converting them to strings? I used JSON.stringify() a lot.

1
2
3
4
5
6
7
8
9
const todo = {
  id: 1,
  userId: 1,
  title: "kill bill",
  completed: false
};

console.log(JSON.stringify(todo));
// {"id":1,"userId":1,"title":"kill bill","completed":false}

I could easily print out everything including the kitchen sink with console and become a wise sage at the end of debugging session.

Things are significantly easier now and have been for more than few years. I can not only print entire objects, but also print them in full techni-color.

1
2
3
4
5
console.log(
  "%c%s",
  "color: white; background: magenta; font-size: 20px;",
  "Program starts with a bang."
);

See more on the right way to use Javascript console in DevTools.

So, is there a place for JSON.stringify() at all?

I will let you decide for yourself, but below are a couple of instances where that could help.

Selective selection!

You can specify which parts of the object to print.

1
2
console.log(JSON.stringify(todo, ["id", "completed"]));
// {"id":1,"completed":false}

We specify which props to select in the above code, which is especially useful in Node when debugging the server-side of things. It can be a pain to just sift through pages of logs using less or staring at a Matrix-like scrolling in tail -f.

Format output

You can also specify how to separate out the elements.

We specify a tab character in the example below.

1
2
3
4
5
6
7
console.log(JSON.stringify(todo, ["id", "completed"], "\t"));
/* output
{
        "id": 1,
        "completed": false
}
*/

Recommendation

Sure, use JSON.stringify() - but sparingly.

You may neither require JSON.stringify() or console.log() - use modern debugging techniques for Node and for Chrome in VS Code :)

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things