Explain Codes LogoExplain Codes Logo

Javascript: How can I generate formatted easy-to-read JSON straight from an object?

javascript
json-stringify
replacer-function
web-development
Anton ShumikhinbyAnton Shumikhin·Aug 3, 2024
TLDR

Raise your JSON readability with the JSON.stringify function. Simply use null and 2 as your magic sauce parameters:

const obj = { title: 'Example', active: true }; const eyeFriendlyJSON = JSON.stringify(obj, null, 2); console.log(eyeFriendlyJSON);

You'll see the following console output in glorious pretty print:

{ "title": "Example", "active": true }

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:

<script src="path/to/json2.js"></script>

Only load it if the Stone Age browser lacks JSON.stringify:

if (!window.JSON) { // Fire up the flux capacitor... Load json2.js }

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:

const user = { name: 'Alice', age: 30, password: 'dangerousSecret' }; const narrowedJSON = JSON.stringify(user, ['name', 'age'], 2); console.log(narrowedJSON);

You get:

{ "name": "Alice", "age": 30 }

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:

function replacer(key, value) { if (typeof value === 'function') { return value.toString(); // Not as terrifying as it seems? } if (value === undefined) { return 'null'; // "I am UnDeFiNeD no more!" } return value; }

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:

<pre id="json-output"></pre>
document.getElementById('json-output').textContent = eyeFriendlyJSON;

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:

JSON.stringify([1, undefined, 3]);

Will result in:

[1, null, 3]

Alternate indentation levels

Spoiler alert: JSON.stringify supports ANY indentation level. You can choose to set the number of spaces between 0 to 10.

const jsonString = JSON.stringify(object, null, 4); // Nested objects adore this!

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.