I often want to "pretty print" (include extra white-space to make it easier for humans to interpret) JavaScript objects, and JSON.stringify(myObject, null, " ") usually suffices for this. However, in many cases, there are arrays of numbers that I really don't want split onto new lines.
Is there a simple/elegant way of accomplishing this with the native JSON.stringify function?
I tried using a "replacer" function but this seems to only facilitate alteration (e.g. modify data), filtering (e.g. omit data), and side-effects (e.g. log data) -- see also How Do I Use The Replacer Function With JSON Stringify?.
Alternatively, is there an established module/library/utility for doing this already or should I write my own?
There appear to be many search results on npm.org for "stringify", but the ones I saw seem to just be variations that either run more efficiently on a particular problem domain or avoid problems related to circular/cyclic data structures.
const obj = {
foo: "bar",
oneLine: [1,2,3],
multipleLines: [{
name: "X",
alsoOneLine: [4,5,6]
}, {
name: "Y"
}]
};
document.write(`
<pre>
// This isn't the output I want.
// The arrays containing only numbers should have their elements
// all printed on the same line.
${JSON.stringify(obj, null, " ")}
</pre>
`);