Explain Codes LogoExplain Codes Logo

Pretty-print JSON using JavaScript

javascript
prompt-engineering
functions
syntax-highlighting
Alex KataevbyAlex Kataev·Mar 2, 2025
TLDR

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:

const prettyJSON = JSON.stringify({ name: "John", age: 30 }, null, 4); console.log(prettyJSON);

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:

const userInfo = { jobTitle: "Developer", name: "John" }; const sortKeys = (obj) => { return Object.keys(obj).sort().reduce((result, key) => { result[key] = obj[key]; return result; }, {}); }; console.log(JSON.stringify(sortKeys(userInfo), null, 4));

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:

function syntaxHighlight(json) { // This is where we add some style 💅 // Watch out for HTML Demogorgons though ⚠️ if (typeof json != 'string') { json = JSON.stringify(json, null, 2); } json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { // OMG! The regex above sure looks like the release date of Half Life 3 🧐 // In reality, though, it's just categorizing all JSON types 🙃 let cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; }); }

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:

<pre id="json"></pre>
document.getElementById('json').innerHTML = syntaxHighlight(prettyJSON);

Add Styles using CSS

By using CSS, give each class a unique color, boosting the visual distinction:

.key { color: green; } /* Key color 💚 */ .string { color: navy; } /* String color 🌊 */ .number { color: darkViolet; } /* Number color 🌌 */ .boolean { color: maroon; } /* Boolean color 🌰 */ .null { color: gold; } /* Null color 🥇 */

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:

const prettyJSONTabs = JSON.stringify({ name: "John", age: 30 }, null, '\t'); console.log(prettyJSONTabs);

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.