How can I pretty-print JSON in JavaScript to make it more readable for humans? I’m looking for solutions that include proper indentation and whitespace, and ideally would also support visual enhancements like colors or font styles.
You can pretty-print JSON in JavaScript using the built-in JSON.stringify() method with the space parameter to add proper indentation and whitespace, or use console methods like console.dir() with color options for terminal output, and for advanced features including syntax highlighting, you can utilize npm packages or custom CSS styling.
Contents
- Basic JSON.stringify() Method
- Console Output Solutions
- HTML Display and Web Applications
- Advanced NPM Packages
- Custom Syntax Highlighting
- Practical Examples
Basic JSON.stringify() Method
The simplest way to pretty-print JSON in JavaScript is using the built-in JSON.stringify() method with its optional third parameter called space. By default, JSON.stringify() outputs minified JSON without any whitespace, but the space parameter allows you to control the indentation.
const data = {
name: "John",
age: 30,
city: "New York",
hobbies: ["reading", "coding", "gaming"],
address: {
street: "123 Main St",
zip: "10001"
}
};
// Pretty-print with 2 spaces indentation
const prettyJson = JSON.stringify(data, null, 2);
console.log(prettyJson);
Output:
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
"coding",
"gaming"
],
"address": {
"street": "123 Main St",
"zip": "10001"
}
}
The space parameter can be:
- A number (0-10) representing the number of spaces for indentation
- A string (like
'\t'for tab characters) to use as indentation nullor omitted for compact output
According to the official documentation, “The space argument may be used to control the spacing in the final JSON string.”
Console Output Solutions
For terminal and console output, you can use Node.js’s built-in console.dir() method with specific options that provide both pretty-printing and color enhancement.
const myObject = {
name: "Example",
value: 123,
nested: {
key: "value"
}
};
// Pretty-print with full expansion and colors
console.dir(myObject, { depth: null, colors: true });
This approach works particularly well in Node.js environments where you want formatted output with visual clarity. The depth: null option ensures complete expansion of nested objects, while colors: true adds color coding to different data types.
As Mozilla Developer Network explains, console.dir() displays an interactive list of the properties of the specified JavaScript object.
HTML Display and Web Applications
When displaying JSON in web applications, you can combine JSON.stringify() with HTML formatting to create readable output.
function displayJsonInHtml(jsonData) {
const prettyJson = JSON.stringify(jsonData, null, 2);
const html = `<pre><code>${escapeHtml(prettyJson)}</code></pre>`;
document.getElementById('json-output').innerHTML = html;
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
For better visual presentation, you can add CSS styling:
.json-container {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 1rem;
font-family: 'Courier New', monospace;
font-size: 14px;
overflow-x: auto;
}
.json-container pre {
margin: 0;
white-space: pre-wrap;
word-wrap: break-word;
}
Advanced NPM Packages
For more sophisticated JSON formatting and syntax highlighting, several NPM packages are available:
pretty-print-json
A comprehensive package that provides both console and HTML output with customizable options:
npm install pretty-print-json
import prettyPrintJson from 'pretty-print-json';
// Convert to HTML with syntax highlighting
const html = prettyPrintJson.toHtml(data, {
indent: 2,
lineNumbers: true,
linkUrls: true,
quoteKeys: true,
trailingCommas: false
});
json-colorizer
A simple console syntax highlighter:
npm install json-colorizer
import jsonColorizer from 'json-colorizer';
const coloredJson = jsonColorizer(data, {
colors: {
key: 'yellow',
string: 'green',
number: 'cyan',
boolean: 'red',
null: 'magenta'
}
});
As described on npmjs.com, this package allows customization of output with options for indentation, line numbers, URL links, and more.
Custom Syntax Highlighting
For complete control over JSON presentation, you can implement custom syntax highlighting using CSS classes:
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
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>';
});
}
Then apply CSS styling:
.json-key { color: #ff6b6b; font-weight: bold; }
.json-string { color: #51cf66; }
.json-number { color: #74c0fc; }
.json-boolean { color: #ffd43b; font-weight: bold; }
.json-null { color: #cc5de8; font-weight: bold; }
Practical Examples
Here’s a complete example showing different approaches to JSON pretty-printing:
Example 1: Basic Console Output
const userData = {
id: 12345,
name: "Alice Johnson",
email: "alice@example.com",
isActive: true,
preferences: {
theme: "dark",
notifications: ["email", "push"],
settings: {
autoSave: true,
maxFileSize: 1024
}
}
};
// Method 1: JSON.stringify with 2 spaces
console.log("Method 1 - JSON.stringify with 2 spaces:");
console.log(JSON.stringify(userData, null, 2));
// Method 2: JSON.stringify with tabs
console.log("\nMethod 2 - JSON.stringify with tabs:");
console.log(JSON.stringify(userData, null, '\t'));
// Method 3: console.dir with colors
console.log("\nMethod 3 - console.dir with colors:");
console.dir(userData, { depth: null, colors: true });
Example 2: HTML Display with Syntax Highlighting
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.json-viewer {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 15px;
font-family: 'Courier New', monospace;
white-space: pre-wrap;
word-wrap: break-word;
}
.json-key { color: #d63384; font-weight: bold; }
.json-string { color: #198754; }
.json-number { color: #0d6efd; }
.json-boolean { color: #fd7e14; }
.json-null { color: #6f42c1; }
</style>
</head>
<body>
<h2>JSON Pretty Print with Syntax Highlighting</h2>
<div id="jsonOutput" class="json-viewer"></div>
<script>
const jsonData = {
"api": "users",
"version": "1.0.0",
"timestamp": new Date().toISOString(),
"data": [
{ "id": 1, "name": "User One", "active": true },
{ "id": 2, "name": "User Two", "active": false }
]
};
function prettyPrintJson(data) {
const jsonString = JSON.stringify(data, null, 2);
const highlighted = jsonString.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
let className = '';
if (/^"/.test(match)) {
className = /:$/.test(match) ? 'json-key' : 'json-string';
} else if (/true|false/.test(match)) {
className = 'json-boolean';
} else if (/null/.test(match)) {
className = 'json-null';
} else {
className = 'json-number';
}
return `<span class="${className}">${match}</span>`;
});
return highlighted;
}
document.getElementById('jsonOutput').innerHTML = prettyPrintJson(jsonData);
</script>
</body>
</html>
Sources
- pretty-print JSON using JavaScript - Stack Overflow
- How to Pretty Print JSON String in JavaScript? - GeeksforGeeks
- JavaScript JSON Pretty Print - Formatting JSON Data
- Pretty
JSON.stringify()Output in JavaScript - The Code Barbarian - How to Pretty JSON Output using JavaScript - DEV Community
- How do I pretty print JSON in JavaScript? - ReqBin
- pretty-print-json - npm
- json-colorizer - npm
- How to Use JavaScript to Display JSON in a Readable Format - Medium
- Pretty Print JSON in Node.js - NullDog
Conclusion
Pretty-printing JSON in JavaScript is essential for human readability during development, debugging, and data presentation. The native JSON.stringify() method with the space parameter provides the simplest solution for basic formatting, while console methods like console.dir() offer enhanced visual output in terminal environments. For web applications, combining JSON formatting with CSS styling or using specialized npm packages like pretty-print-json provides the most comprehensive solution with syntax highlighting and customizable styling. Choose the approach that best fits your specific needs based on the environment (console, browser, or Node.js) and the level of visual enhancement required.