How to Format JSON in JavaScript

Learn how to format JSON in JavaScript with built-in methods. Step-by-step tutorial with code examples for pretty-printing and minifying JSON.

How to Format JSON in JavaScript

Working with JSON in JavaScript is common, but raw JSON can be hard to read. This tutorial shows you how to format JSON in JavaScript using built-in methods—no external libraries required. You'll learn to pretty-print JSON with proper indentation and minify it for production.

The Problem with Raw JSON

APIs often return minified JSON like this:

{"user":{"id":1,"name":"John","email":"[email protected]","address":{"city":"NYC","zip":"10001"}}}

This is efficient for transmission but impossible to read. Formatted JSON is much clearer:

{
  "user": {
    "id": 1,
    "name": "John",
    "email": "[email protected]",
    "address": {
      "city": "NYC",
      "zip": "10001"
    }
  }
}

Method 1: JSON.stringify with Indentation (Recommended)

The simplest way to format JSON is using JSON.stringify() with the space parameter:

const data = {
  user: {
    id: 1,
    name: "John",
    email: "[email protected]",
    address: {
      city: "NYC",
      zip: "10001"
    }
  }
};

// Pretty print with 2-space indentation const formatted = JSON.stringify(data, null, 2); console.log(formatted);

Output:

{
  "user": {
    "id": 1,
    "name": "John",
    "email": "[email protected]",
    "address": {
      "city": "NYC",
      "zip": "10001"
    }
  }
}

Parameters Explained

JSON.stringify(value, replacer, space)

| Parameter | Description | Example | |-----------|-------------|---------| | value | The object to stringify | Your data object | | replacer | Optional filter (use null for all) | null or array of keys | | space | Indentation (number or string) | 2, 4, or "\t" |

Custom Indentation Examples

// 4-space indentation
JSON.stringify(data, null, 4);

// Tab indentation JSON.stringify(data, null, '\t');

// No spaces (minified) JSON.stringify(data);

Method 2: Formatting a JSON String

If you already have a JSON string (not an object), parse it first:

const jsonString = '{"user":{"id":1,"name":"John"}}';

// Parse then stringify with formatting const formatted = JSON.stringify(JSON.parse(jsonString), null, 2); console.log(formatted);

With Error Handling

function formatJsonString(jsonString, indent = 2) {
  try {
    const parsed = JSON.parse(jsonString);
    return JSON.stringify(parsed, null, indent);
  } catch (error) {
    console.error('Invalid JSON:', error.message);
    return null;
  }
}

// Usage const raw = '{"broken": json}'; const formatted = formatJsonString(raw); if (formatted) { console.log(formatted); }

Method 3: Minifying JSON for Production

To reduce file size, remove all whitespace:

const data = { name: "John", age: 30 };

// Minified JSON const minified = JSON.stringify(data); // {"name":"John","age":30}

// Or minify a formatted JSON string const formatted = '{\n "name": "John"\n}'; const minified = JSON.stringify(JSON.parse(formatted));

Advanced Formatting Techniques

Custom Replacer Function

Control which values get included:

const data = {
  password: 'secret123',
  email: '[email protected]',
  age: 30
};

// Remove sensitive fields const formatted = JSON.stringify(data, (key, value) => { if (key === 'password') return undefined; return value; }, 2);

console.log(formatted); // { // "email": "[email protected]", // "age": 30 // }

Sorting Keys Alphabetically

function sortObjectKeys(obj) {
  if (typeof obj !== 'object' || obj === null) return obj;
  if (Array.isArray(obj)) return obj.map(sortObjectKeys);

return Object.keys(obj).sort().reduce((result, key) => { result[key] = sortObjectKeys(obj[key]); return result; }, {}); }

const data = { zebra: 1, apple: 2, banana: 3 }; const sorted = sortObjectKeys(data); const formatted = JSON.stringify(sorted, null, 2);

Formatting Large JSON Files

For very large JSON objects, use a streaming approach:

// For Node.js with large files
const fs = require('fs');

const readable = fs.createReadStream('large.json'); let data = '';

readable.on('data', (chunk) => { data += chunk; });

readable.on('end', () => { const parsed = JSON.parse(data); const formatted = JSON.stringify(parsed, null, 2); fs.writeFileSync('formatted.json', formatted); });

Browser Console Quick Format

For quick formatting in browser DevTools:

// Paste this in console with your JSON
console.log(JSON.stringify(yourJsonObject, null, 2));

// Or use table for array data console.table(yourArray);

Complete Example: JSON Formatter Utility

class JsonFormatter {
  static format(data, indent = 2) {
    try {
      // If string, parse first
      const parsed = typeof data === 'string' ? JSON.parse(data) : data;
      return JSON.stringify(parsed, null, indent);
    } catch (error) {
      throw new Error(Invalid JSON: ${error.message});
    }
  }

static minify(data) { const parsed = typeof data === 'string' ? JSON.parse(data) : data; return JSON.stringify(parsed); }

static validate(data) { try { if (typeof data === 'string') { JSON.parse(data); } return true; } catch { return false; } } }

// Usage const formatted = JsonFormatter.format({ name: "John" }); const minified = JsonFormatter.minify({ name: "John" }); const isValid = JsonFormatter.validate('{ broken }');

Try It Yourself

Want to format JSON without writing code? Try our JSON Formatter for instant pretty-printing with syntax highlighting and error detection.

Conclusion

Formatting JSON in JavaScript is simple with JSON.stringify(data, null, 2). Use 2-space indentation for readability, minify for production, and always validate JSON before parsing.

For more JSON tools, check out our guide on How to Decode a JWT Token which also involves JSON parsing.

---

Related Tools:

🚀 Deploy Your Own Tools — Recommended Hosting

Want to self-host or build your own developer tools? These are the platforms we use:

🌐
Hostinger
Web Hosting from $2.99/mo
💧
DigitalOcean
$200 Free Credit for New Users
🔑
Namecheap
Domains from $0.99/yr

* Affiliate links — we may earn a commission at no extra cost to you.

🔥 Limited Time Offer — Starting at $5

Get instant access to premium developer tools — exclusive discount ends soon!

🛠️

AI 工具数据库

82 个开发者工具离线版

👥 50+ developers purchased

$9 立即获取 →
📝

SEO 内容包

100 篇开发者文章

👥 30+ developers purchased

$19 立即获取 →
💎

空投狩猎指南 2026

从零成本到高级技巧

👥 25+ developers purchased

$5 立即获取 →

❤️ Support Independent Development

Love these free tools? Help keep them ad-free forever with a small contribution.

💙 Your support keeps these tools free for everyone