DEV Community

Pretty JSON Output

Samantha Ming on January 28, 2019

Tired of the one-liner JSON output, well no more! Utilize JSON.stringify built-in pretty printing. Set the 3rd parameter with your desired spacin...
Collapse
 
qm3ster profile image
Mihail Malo

Doesn't seem like the output of JSON.stringify(protein, null, "I ๐Ÿ’›") is recoverable with JSON.parse.

Collapse
 
samanthaming profile image
Samantha Ming

oh ya ๐Ÿ˜ฎ ...looking into the docs. it seems like:
Throws a SyntaxError exception if the string to parse is not valid JSON.

Definitely something to keep in mind before using the "space" parameter. thanks for catching that!

Collapse
 
qm3ster profile image
Mihail Malo • Edited

I was just curious if there would be a way to recover, for example another parameter you could pass to parse. There isn't though.

const protein = {
  steak: "๐Ÿฅฉ",
  bacon: "๐Ÿฅ“",
  fake: { shrimp: "๐Ÿค" },
  array: ["๐Ÿฅฉ", "๐Ÿฅ“", "๐Ÿค"]
}
// looks weird but works
JSON.parse(JSON.stringify(protein, null, "\n\t\n\0\r  "))
// SyntaxError
JSON.parse(JSON.stringify(protein, null, "๐Ÿฅ“"))

// and my favorite:
// parses as `{sh: "๐Ÿค", steak: "๐Ÿฅฉ", bacon: "๐Ÿฅ“"}`
// but breaks nested objects or arrays.
JSON.parse(JSON.stringify({ steak: "๐Ÿฅฉ", bacon: "๐Ÿฅ“" }, null, '"sh":"๐Ÿค",'))
Collapse
 
papagoat profile image
Terence Lucas Yap

This is awesome. Never really bothered to discover all these features. Thumbs up. :)

Collapse
 
samanthaming profile image
Samantha Ming

You're welcome! Glad you found it helpful ๐Ÿ‘

Collapse
 
thompcd profile image
Corey Thompson

Thank you! Saved me quite a bit of searching :)

Collapse
 
samanthaming profile image
Samantha Ming

Glad the tidbit was helpful! Thanks for reading the article ๐Ÿ˜„

Collapse
 
samanthaming profile image
Samantha Ming

Thanks! ๐Ÿ˜„