Javascript: How can I generate formatted easy-to-read JSON straight from an object?
Raise your JSON readability with the JSON.stringify
function. Simply use null
and 2
as your magic sauce parameters:
You'll see the following console output in glorious pretty print:
So, there you are — JSON.stringify
magically transforms your object into a prettified string with two space indentation. Your eyes will thank you, trust me.
Digging deeper
Power beyond pretty printing lies within the JSON.stringify
. Learn how to apply this function for maximum code readability and compatibility
Workaround for older browsers
Wipe the dust off your older browsers, JSON.stringify
has got your back. However, for browsers that are so old, even dinosaurs used them, lean on the json2.js library:
Only load it if the Stone Age browser lacks JSON.stringify
:
Choose your JSON content
Why display the whole JSON object when all you need are certain elements? The second parameter of JSON.stringify
is for this purpose. You can provide either a replacer function or an array of property names:
You get:
In this way, dangerousSecret
won't slip into innocent hands.
Handling troublesome content
JSON.stringify
tends to panic when spotting functions, undefined
, or circular references in your object, either skipping them or throwing a ‘temper tantrum’. Hence, use a custom replacer function to pacify the panicking function:
Displaying JSON on the web
Who doesn't love elegant JSON on a webpage? Remember to wrap your output in a <pre>
tag. This maintains the formatting of your JSON:
Your elegantly displayed JSON would be the talk of the browser town!
Pro tips and tricks
Mind the null and undefined
Even though you can set the undefined
in the object as 'null'
with a replacer function, remember this: undefined
is transformed into null
by default when it emerges as an array element:
Will result in:
Alternate indentation levels
Spoiler alert: JSON.stringify
supports ANY indentation level. You can choose to set the number of spaces between 0
to 10
.
For humongous objects
For Goliath-sized objects, stringify the entire thing at once and you might need an Asprin for the performance headache. Consider chunking the object or streaming the data server-side.
For Node.js developers
Node.js savvies can utilize the util.inspect()
function to convert an object into a string with extra control over the output format.
Was this article helpful?