How to Format JSON in JavaScript: Complete Guide
Learn all the methods to format, stringify, and beautify JSON in JavaScript. From basic JSON.stringify() to advanced formatting techniques.
Quick Answer: JSON.stringify() with Formatting
The fastest way to format JSON in JavaScript is using JSON.stringify()
with the space parameter for indentation:
// Basic JSON formatting
const data = { name: "John", age: 30, city: "New York" };
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// Output:
{
"name": "John",
"age": 30,
"city": "New York"
}
Understanding JSON.stringify() Parameters
JSON.stringify()
accepts three parameters that give you full control over JSON formatting:
Syntax
JSON.stringify(value, replacer, space)
- value: The JavaScript object to convert
- replacer: Function or array to filter/transform properties
- space: Number of spaces or string for indentation
1. Basic Formatting with Indentation
const user = {
id: 1,
name: "Alice",
email: "alice@example.com",
preferences: {
theme: "dark",
notifications: true
}
};
// 2 spaces indentation (most common)
const formatted2 = JSON.stringify(user, null, 2);
// 4 spaces indentation
const formatted4 = JSON.stringify(user, null, 4);
// Tab indentation
const formattedTab = JSON.stringify(user, null, '\t');
2. Custom Formatting with Replacer Function
Use a replacer function to filter or transform properties during formatting:
const userData = {
id: 123,
name: "Bob",
password: "secret123",
email: "bob@example.com",
lastLogin: new Date()
};
// Remove sensitive data and format dates
const safeReplacer = (key, value) => {
// Remove password field
if (key === 'password') return undefined;
// Format dates as ISO strings
if (value instanceof Date) return value.toISOString();
return value;
};
const formatted = JSON.stringify(userData, safeReplacer, 2);
console.log(formatted);
// Output:
{
"id": 123,
"name": "Bob",
"email": "bob@example.com",
"lastLogin": "2024-01-15T10:30:00.000Z"
}
3. Property Filtering with Array Replacer
const product = {
id: 456,
name: "Laptop",
price: 999.99,
inStock: true,
warehouse: "A1",
supplier: "TechCorp"
};
// Only include specific properties
const publicFields = ['id', 'name', 'price', 'inStock'];
const publicData = JSON.stringify(product, publicFields, 2);
// Output:
{
"id": 456,
"name": "Laptop",
"price": 999.99,
"inStock": true
}
Advanced JSON Formatting Techniques
Custom JSON Formatter Function
Create a reusable function for consistent JSON formatting across your application:
function formatJSON(obj, options = {}) {
const {
indent = 2,
sortKeys = false,
removeEmpty = false,
dateFormat = 'iso'
} = options;
const replacer = (key, value) => {
// Remove null/undefined/empty values if requested
if (removeEmpty && (value === null || value === undefined || value === '')) {
return undefined;
}
// Format dates
if (value instanceof Date) {
return dateFormat === 'iso' ? value.toISOString() : value.toString();
}
return value;
};
let result = JSON.stringify(obj, replacer, indent);
// Sort keys if requested
if (sortKeys) {
const parsed = JSON.parse(result);
result = JSON.stringify(sortObjectKeys(parsed), null, indent);
}
return result;
}
function sortObjectKeys(obj) {
if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
return obj;
}
const sorted = {};
Object.keys(obj).sort().forEach(key => {
sorted[key] = sortObjectKeys(obj[key]);
});
return sorted;
}
// Usage
const data = { z: 1, a: 2, m: { b: 3, a: 4 } };
console.log(formatJSON(data, { sortKeys: true }));
Formatting JSON with Error Handling
function safeJSONFormat(data, indent = 2) {
try {
// Handle circular references
const seen = new WeakSet();
const replacer = (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular Reference]';
}
seen.add(value);
}
return value;
};
return JSON.stringify(data, replacer, indent);
} catch (error) {
console.error('JSON formatting error:', error.message);
return `Error: ${error.message}`;
}
}
// Test with circular reference
const obj = { name: "Test" };
obj.self = obj; // Creates circular reference
console.log(safeJSONFormat(obj)); // Won't throw error
Common JSON Formatting Patterns
API Response Formatting
// Format API response for debugging
function debugAPI(response) {
console.log('API Response:');
console.log(JSON.stringify(response, null, 2));
}
// Format for logging with timestamp
function logJSON(data, label = '') {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${label}`);
console.log(JSON.stringify(data, null, 2));
}
// Pretty print in development, minify in production
function formatForEnvironment(data) {
return process.env.NODE_ENV === 'development'
? JSON.stringify(data, null, 2)
: JSON.stringify(data);
}
Configuration File Generation
function generateConfig(options) {
const config = {
version: "1.0.0",
environment: options.env || "development",
database: {
host: options.dbHost || "localhost",
port: options.dbPort || 5432,
name: options.dbName
},
features: {
authentication: true,
logging: options.env !== "production",
caching: options.env === "production"
}
};
// Format with comments (for .json files that support them)
return JSON.stringify(config, null, 2);
}
const devConfig = generateConfig({
env: "development",
dbHost: "localhost",
dbName: "myapp_dev"
});
console.log(devConfig);
Best Practices for JSON Formatting
Use Consistent Indentation
Stick to 2 or 4 spaces consistently across your project. Most JavaScript projects use 2 spaces.
Handle Circular References
Always implement circular reference detection when formatting unknown data structures.
Format for Your Audience
Use pretty formatting for development/debugging, minified for production/APIs.
Filter Sensitive Data
Use replacer functions to remove passwords, tokens, and other sensitive information.
Common Pitfalls and Solutions
Circular Reference Error
Problem: TypeError: Converting circular structure to JSON
Solution: Use a WeakSet to track visited objects and detect circles.
Date Serialization Issues
Problem: Dates become strings and lose their Date type
Solution: Use replacer function to format dates consistently or include type hints.
Performance with Large Objects
Tip: JSON.stringify() can be slow with very large objects
Solution: Use streaming JSON parsers for large datasets or implement pagination.
Testing Your JSON Formatting
// Unit test example for JSON formatting
function testJSONFormatting() {
const testData = {
string: "test",
number: 42,
boolean: true,
array: [1, 2, 3],
object: { nested: "value" }
};
// Test basic formatting
const formatted = JSON.stringify(testData, null, 2);
console.assert(formatted.includes(' "string"'), 'Should have 2-space indentation');
// Test property filtering
const filtered = JSON.stringify(testData, ['string', 'number'], 2);
console.assert(!filtered.includes('boolean'), 'Should filter out non-listed properties');
// Test circular reference handling
testData.self = testData;
try {
JSON.stringify(testData);
console.error('Should have thrown circular reference error');
} catch (e) {
console.log('✓ Circular reference correctly detected');
}
}
testJSONFormatting();
Try Our Online JSON Formatter
Test your JSON formatting skills with our free online tool. Format, validate, and beautify JSON instantly without writing any code.
Summary
JSON formatting in JavaScript is straightforward with JSON.stringify()
, but mastering the replacer and space parameters gives you powerful control over output. Remember to handle edge cases like circular references and sensitive data, and choose formatting styles that match your use case—pretty for development, minified for production.
Key Takeaways:
- Use
JSON.stringify(obj, null, 2)
for basic pretty formatting - Implement replacer functions for data filtering and transformation
- Handle circular references to avoid runtime errors
- Choose indentation styles consistently across your project
- Test your formatting functions with edge cases