How do you pretty-print formatted JSON with indentation in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you pretty-print formatted JSON with indentation in JavaScript?

message-square
0

To pretty-print formatted JSON with indentation in JavaScript, pass an indentation spacing argument (such as 2 or 4 spaces) as the third argument to JSON.stringify(value, replacer, space). Passing null for the second (replacer) argument keeps all serializable properties while applying clean multi-line formatting.


1. Pretty-Printing with JSON.stringify(data, null, 2)

Provide a number from 1 to 10 (commonly 2 or 4) for space to indent nested objects and arrays with that number of spaces per level:

// Pretty-print a JavaScript value as indented JSON
function formatPrettyJson(data, indentSpaces = 2) {
  return JSON.stringify(data, null, indentSpaces);
}

const userSession = {
  userId: 104,
  username: "amina_k",
  active: true,
  roles: ["editor", "reviewer"],
  preferences: {
    theme: "dark",
    compactMode: false
  }
};

const prettyJson = formatPrettyJson(userSession, 2);
console.log(prettyJson);
  • Third argument (space): Controls indentation width (2 is standard for config/logs/APIs; values above 10 clamp to 10).
  • Second argument (replacer): Pass null to include all enumerable properties, or supply a function/array to filter or transform fields during serialization.
  • Returns a string: Output is a formatted JSON string ready for logging, <pre> display, or writing to disk.

2. Custom Indentation Strings and Filtering Fields with replacer

JSON.stringify() also accepts a string (such as "\t" for tabs) as the space parameter and supports a replacer function when you want to redact secrets or format specific keys while pretty-printing:

// Pretty-print with tab indentation and redact sensitive fields via replacer
function formatSafeJson(data, indent = "\t") {
  const redactedKeys = new Set(["password", "token", "secret"]);

  return JSON.stringify(
    data,
    (key, value) => (redactedKeys.has(key) ? "[REDACTED]" : value),
    indent
  );
}

const authDebug = {
  sessionId: "sess_8891",
  token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
  meta: { ip: "192.168.1.10" }
};

console.log(formatSafeJson(authDebug, "  "));
  • Tab or custom prefix indentation: Passing "\t" indents with tab characters; passing a string like "-- " prefixes each level with that string (up to 10 characters).
  • Safe log/debug output: Redacting sensitive keys inside the replacer avoids leaking tokens or credentials in formatted logs.

3. Common Traps to Avoid

Pretty-printing JSON in JavaScript runs into a few subtle pitfalls:

  • Passing an already-parsed vs. raw JSON string: JSON.stringify() expects a JavaScript value—if you already have a raw JSON string, parse it with JSON.parse(rawJson) first before calling JSON.stringify(parsed, null, 2) (otherwise JSON.stringify() escapes quotes inside a string).
  • Circular references throwing a TypeError: If an object references itself (obj.self = obj), JSON.stringify() throws Converting circular structure to JSON unless handled or stripped in a replacer.
  • Non-JSON types being omitted or altered: Functions, undefined object properties, and Symbol keys are skipped in objects, while BigInt throws unless converted to a string/number.

TL;DR: Use JSON.stringify(data, null, 2) to format JavaScript data into readable, 2-space indented JSON—and parse raw JSON strings with JSON.parse() first if you are reformatting an existing JSON string.

Are you pretty-printing objects for console/file logs, reformatting an existing JSON string, or filtering/redacting fields during serialization?