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 i…


This content originally appeared on DEV Community and was authored by Siddharth

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}
// }

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"
//   }
// }

Hope this helps you while debugging sometime!


This content originally appeared on DEV Community and was authored by Siddharth


Print Share Comment Cite Upload Translate Updates
APA

Siddharth | Sciencx (2021-05-25T15:08:17+00:00) Pretty printing JSON.stringify. Retrieved from https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/

MLA
" » Pretty printing JSON.stringify." Siddharth | Sciencx - Tuesday May 25, 2021, https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/
HARVARD
Siddharth | Sciencx Tuesday May 25, 2021 » Pretty printing JSON.stringify., viewed ,<https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/>
VANCOUVER
Siddharth | Sciencx - » Pretty printing JSON.stringify. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/
CHICAGO
" » Pretty printing JSON.stringify." Siddharth | Sciencx - Accessed . https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/
IEEE
" » Pretty printing JSON.stringify." Siddharth | Sciencx [Online]. Available: https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/. [Accessed: ]
rf:citation
» Pretty printing JSON.stringify | Siddharth | Sciencx | https://www.scien.cx/2021/05/25/pretty-printing-json-stringify/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.