Pretty-print JSON using JavaScript
Pretty-print regular JSON data by using JSON.stringify()
: serialize your data as the first parameter, null
as the second to avoid filtering properties, and a number amounting to 4 as the third for specifying indentation:
The above outputs well-arranged and human-readable JSON with four spaces as indentation at each level.
Key sorting for better readability
Before converting the JSON object into a string, sorting your object's keys enhances consistent order, aiding users in brisk navigation and interpretability:
Impart Colours with Syntax Highlighting
For eye-catchy syntax highlighting, we tailor a function that wraps different types of JSON values in <span>
elements, then applying the appropriate classes:
Displaying with HTML and CSS
Enclose your JSON text within HTML <pre>
tags to maintain its format. Leveraging innerHTML
, insert the embellished JSON text in the HTML view:
Add Styles using CSS
By using CSS, give each class a unique color, boosting the visual distinction:
More ways to pretty-print JSON
Indentation with tabs
For those in the 'tabs for life' camp, swap the space indentation argument with '\t' like so:
Styling tweaks
Unleash your inner artist with CSS. Enrich font styles, background colors, and more to augment readability ad aesthetics.
Embrace online tools
Ease life and leverage online tools such as JSONLint and Code Beautify for speedy validation and formatting while giving room for customization.
Understand better
Heighten your grasp on JSON structures by narrowing on vital elements like variable types, nested structures, etc. Recognize and rectify common mistakes like falling commas or mismatched brackets that break parsing.
Was this article helpful?