I need to display JSON in a human-readable format with proper indentation and whitespace. Ideally, I’d also like to add some styling, like colors or font styles, to make it easier to read.
What’s the best way to javascript json pretty print for clear, formatted output?
I’ve worked with JavaScript long enough to know that sometimes the simplest tools are the most overlooked. For a quick and clean javascript json pretty print, I always start here:
const jsonData = { name: "Alice", age: 30, city: "Wonderland" };
const pretty = JSON.stringify(jsonData, null, 2);
console.log(pretty);
That 2
is the magic sauce—it controls the indentation (spaces), and you can tweak it to your liking. This method is perfect when you just want legible JSON in your logs or a quick inspection in your console. No fuss, no dependencies.
Totally agree with Joe it’s a solid starting point. But let’s say you want to bring that javascript json pretty print to the browser for users to actually see it on the page. Here’s how I usually do it using the <pre>
tag:
const jsonData = { name: "Alice", age: 30 };
document.body.innerHTML = `<pre>${JSON.stringify(jsonData, null, 4)}</pre>`;
Now the JSON is not just formatted—it’s displayed as-is, with all the structure preserved visually. This is super useful for building tools, dashboards, or debug UIs. A sprinkle of padding and a monospace font via CSS, and you’ve got a user-friendly data dump right on the screen.
Nice! But if you’ve ever had to explain large or complex JSON data to someone non-technical or even just want quicker visual parsing then adding some color makes a huge difference. Here’s how I take javascript json pretty print a step further with syntax highlighting:
function syntaxHighlight(json) {
json = JSON.stringify(json, null, 2);
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\""])*"(:)?|\b(true|false|null)\b|\d+)/g, match => {
let cls = 'number';
if (/^"/.test(match)) {
cls = /:$/.test(match) ? 'key' : 'string';
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return `<span class="${cls}">${match}</span>`;
});
}
const jsonData = { name: "Alice", age: 30, active: true };
document.body.innerHTML = `<pre>${syntaxHighlight(jsonData)}</pre>`;
Just pair this with some CSS like:
.key { color: brown; }
.string { color: green; }
.number { color: blue; }
.boolean { color: purple; }
.null { color: gray; }
Boom!!! your avascript json pretty print is now both human-readable and aesthetically pleasant. Great for tools, APIs, or even just impressing your teammates. 