DEV Community

Discussion on: Pretty JSON Output

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":"๐Ÿค",'))