Json.stringify output to div in pretty print way
Achieve JSON pretty print in HTML by specifying indentation in JSON.stringify
and assigning to textContent
of your div
:
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:
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:
Advanced string manipulations
Consider using newer JS features like String.repeat
for even more sophistication in your custom formatting and presentation logic:
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:
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:
Utilising popular libraries
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:
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.
Was this article helpful?