DEV Community

Siddharth
Siddharth

Posted on

Pretty printing JSON.stringify

Most of use JSON.stringify a lot to avoid the infamous "[object Object]". But did you know that it had a few more arguments?

JSON.stringify takes a total of 3 arguments. The first one is the data, the second is a replacer function, and the third one is the indentation.

The main topic of this article is the third argument. If you provide a string as the third argument, that string will be used as indentation. Here's an example:

JSON.stringify({a: 'B', c: {d: 'e'}})
// => {"a":"B","c":{"d":"e"}}
JSON.stringify({a: 'B', c: {d: 'e'}}, null, "  ")
// => 
// {
//   "a": "B",
//   "c": {
//     "d": "e"
//   }
// }
JSON.stringify({a: 'B', c: {d: 'e'}}, null, "test")
// =>
// {
// test"a": "B",
// test"c": {
// testtest"d": "e"
// test}
// }
Enter fullscreen mode Exit fullscreen mode

You can also pass in a number instead. If you do so, that many spaces will be inserted as indentation:

JSON.stringify({a: 'B', c: {d: 'e'}}, null, 2)
// => 
// {
//   "a": "B",
//   "c": {
//     "d": "e"
//   }
// }
Enter fullscreen mode Exit fullscreen mode

Hope this helps you while debugging sometime!

Top comments (0)