How to Pretty Print JSON: Formatting Techniques Explained
Master JSON formatting and pretty printing. Learn multiple methods to make JSON readable and maintainable.
Pretty printing JSON transforms compressed, hard-to-read data into nicely formatted, indented output. This fundamental technique improves code readability, aids debugging, and enhances collaboration among developers.
What is Pretty Printing?
Pretty printing adds whitespace (indentation and line breaks) to JSON data while preserving its structure and values. It transforms minified JSON into a human-readable format.
Before (Minified):
{"users":[{"id":1,"name":"Alice","email":"alice@example.com"},{"id":2,"name":"Bob","email":"bob@example.com"}]}
After (Pretty Printed):
{
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com"
}
]
}
Method 1: JavaScript's JSON.stringify()
The simplest approach in JavaScript uses the built-in JSON.stringify() method with formatting parameters:
const data = { name: "John", age: 30, hobbies: ["reading", "coding"] };
// Pretty print with 2-space indentation
const prettyJSON = JSON.stringify(data, null, 2);
console.log(prettyJSON);
// Pretty print with 4-space indentation
const pretty4 = JSON.stringify(data, null, 4);
Understanding the Parameters
- First parameter: The object to stringify
- Second parameter: A replacer function or array (use null to include everything)
- Third parameter: Number of spaces or string for indentation
Method 2: Using Online Tools
FormatCraft's JSON Formatter provides instant pretty printing without writing code. Simply paste your JSON and click the Format button.
Method 3: Command Line Tools
Using Python
# Pretty print JSON from a file
python -m json.tool input.json > output.json
# Pretty print from clipboard
cat input.json | python -m json.tool
Using Node.js
# Install globally
npm install -g js-beautify
# Pretty print a file
js-beautify input.json > output.json
Method 4: IDE Extensions
Most modern IDEs support JSON formatting:
Visual Studio Code:
- Open JSON file
- Right-click → Format Document
- Or press Shift + Alt + F
WebStorm/IntelliJ:
- Open JSON file
- Code → Reformat Code
- Or press Ctrl + Alt + L (Windows) or Cmd + Alt + L (Mac)
Advanced Pretty Printing
Custom Replacer Function
Control which fields appear in output:
const data = {
username: "alice",
password: "secret123",
email: "alice@example.com"
};
// Exclude password from output
const sanitized = JSON.stringify(data, (key, value) => {
return key === 'password' ? undefined : value;
}, 2);
Custom Indentation
Use different indentation styles:
// Tab indentation
const tabIndented = JSON.stringify(data, null, ' ');
// 4-space indentation
const fourSpace = JSON.stringify(data, null, 4);
// Custom string
const custom = JSON.stringify(data, null, ' > ');
Best Practices
1. Development vs Production
Use pretty printing during development for readability:
const isDevelopment = process.env.NODE_ENV === 'development';
const jsonString = JSON.stringify(data, null, isDevelopment ? 2 : undefined);
2. Preserve Formatting
When storing formatted JSON, maintain consistency:
// Always use 2-space indentation for consistency
const formatted = JSON.stringify(data, null, 2);
fs.writeFileSync('data.json', formatted);
3. Debug Complex Objects
Pretty print objects during debugging:
console.log(JSON.stringify(complexObject, null, 2));
4. Log with Formatting
Enhance logging output:
function debugLog(data) {
console.log(JSON.stringify(data, null, 2));
}
Performance Considerations
Pretty printing has minimal performance impact during development but should be avoided in production APIs. The extra characters increase bandwidth usage without benefit to end users.
Size Impact
- Original: 156 bytes (minified)
- Pretty printed (2-space): 258 bytes (+65%)
- Pretty printed (4-space): 320 bytes (+105%)
Common Scenarios
API Response Logging
Pretty print API responses for debugging:
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
Configuration Files
Store configuration as pretty-printed JSON:
const config = { database: "postgres", port: 5432 };
fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
Testing and Validation
Use pretty printing when writing test fixtures:
const testData = {
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]
};
console.log(JSON.stringify(testData, null, 2));
Pretty printing is an essential skill for developers working with JSON data. Whether using built-in language features or dedicated tools, properly formatted JSON significantly improves your development experience and debugging efficiency.
Average reading pace: 200 words per minute
Share Article
Related Articles
How to Fix Invalid JSON: A Practical Debugging Guide
Learn practical techniques to identify and fix JSON syntax errors. Discover common mistakes and how to validate your data structures effectively.
Understanding Common JSON Parse Errors and Solutions
Explore the most common JSON parse errors developers encounter. Learn what causes each error and how to resolve them quickly.
JSON vs XML: Choosing the Right Data Format
Compare JSON and XML formats for data interchange. Understand the strengths, weaknesses, and use cases of each format.