Explain Codes LogoExplain Codes Logo

Json.stringify output to div in pretty print way

javascript
json-stringify
pretty-print
html-tag
Anton ShumikhinbyAnton Shumikhin·Oct 19, 2024
TLDR

Achieve JSON pretty print in HTML by specifying indentation in JSON.stringify and assigning to textContent of your div:

var data = { "user": "Alice", "role": "admin" }; document.getElementById("display").textContent = JSON.stringify(data, null, 2);

This applies an indentation of 2 spaces to your JSON data when outputted in your div to create formatted readability.

Using <pre> tag for displaying JSON

The <pre> tag lets you display HTML text formatting as coded, so the browser presents any spaces and line breaks that exist. It's best suited for pretty printed JSON. Here's how:

<pre id="json-pretty"></pre>
var jsonData = { "user": "Alice", "role": "admin" }; document.getElementById("json-pretty").textContent = JSON.stringify(jsonData, null, 2);

Advanced JSON visualization techniques

Customize your indentation

What if our standard two-space indentation doesn't make your developer heart get butterflies? Well, JSON.stringify allows for variety, according to your taste:

// 4 spaces? Why not! document.getElementById('json-pretty').textContent = JSON.stringify(data, null, 4);

Advanced string manipulations

Consider using newer JS features like String.repeat for even more sophistication in your custom formatting and presentation logic:

function prettyPrintJSON(jsonData) { // Can be as novel as your next npm package! }

Manual formatting without <pre>

Sometimes you might need to eschew the convenience of <pre>. In those cases — here's an example of doing it the gritty, hands-dirty way as a regex warrior:

function formatJSONForDiv(jsonData) { return JSON.stringify(jsonData, null, 2) .replace(/\n/g, '<br>') // Turns line breaks into HTML ones .replace(/\s\s/g, '&nbsp;&nbsp;'); // Convert spaces into HTML ones. Find-and-replace nostalgia, anyone? }

It does require more work, so unless you enjoy regex, it's an "only if necessary" solution.

IIFEs with JSON

IIFEs (Immediately Invoked Function Expression) can also be used to asynchronously parse and display JSON:

(function displayJSON() { var jsonData = { user: "Alice", roles: ["admin", "editor"] }; document.getElementById('json-container').textContent = JSON.stringify(jsonData, null, 2); })(); // Just can't wait to be invoked!

Lay your hands on "nodedump"

For complex JSON, consider resources like "nodedump" on GitHub. It provides advanced formatting and syntax highlighting — a life-saver for developers working with intricately complex data structures.

A little jQuery doesn't hurt

If you're familiar with jQuery, beautifying JSON becomes even simpler, utilizing sleek .text() or .html() functions to inject the JSON into the DOM:

$('#json-pretty').text(JSON.stringify(data, null, 2)); // or for HTML formatting a JSON in a pinch! $('#json-rich').html(formatJSONForDiv(data));

Taking care of design & performance aspects

Page layout may brake. Like car brakes.

Preformatted text can affect your page's layout and design. You don't want your beautiful JSON to create an ugly overall impression, so always test in variable contexts to ensure a seamless user experience.

User experience goes beyond appearance

Rendering large bodies of JSON on a webpage can impact not only how it looks. You also need to consider the performance and accessibility aspects. It's like printing a full novel on a single page! Think about lazy loading or asynchronous data fetching for managing large datasets.