How to pretty-print JSON using JavaScript?

To pretty-print JSON in JavaScript, you can use the built-in JSON.stringify() method with formatting options. Here’s how to do it in different scenarios:

1. Basic Pretty-Print

const data = { name: "Alice", age: 30, hobbies: ["coding", "reading"] };
const prettyJSON = JSON.stringify(data, null, 2); // 2 spaces for indentation
console.log(prettyJSON);

Output:

{
  "name": "Alice",
  "age": 30,
  "hobbies": [
    "coding",
    "reading"
  ]
}

2. With Tabs Instead of Spaces

const compactPrint = JSON.stringify(data, null, '\t'); // Use tabs
console.log(compactPrint);

Output:

{
    "name": "Alice",
    "age": 30,
    "hobbies": [
        "coding",
        "reading"
    ]
}

3. Pretty-Print a JSON String

If your input is a JSON string, parse it first:

const jsonString = '{"name":"Bob","details":{"age":25}}';
const parsedData = JSON.parse(jsonString);
console.log(JSON.stringify(parsedData, null, 2));

4. Pretty-Print in the Browser Console

For debugging, use console.dir to display formatted JSON objects:

console.dir(data, { depth: null, colors: true }); // Node.js or DevTools

5. Custom Replacer Function (Optional)

Filter or modify keys during formatting:

const replacer = (key, value) => {
  if (key === "age") return undefined; // Hide the "age" property
  return value;
};

console.log(JSON.stringify(data, replacer, 2));

Output:

{
  "name": "Alice",
  "hobbies": [
    "coding",
    "reading"
  ]
}

6. Error Handling

Wrap in a try...catch to handle invalid JSON:

try {
  const uglyJSON = "{invalid: json}";
  const parsed = JSON.parse(uglyJSON);
  console.log(JSON.stringify(parsed, null, 2));
} catch (err) {
  console.error("Invalid JSON:", err.message);
}

Key Notes

  • JSON.stringify(value, replacer, space):
  • replacer: Function or array to filter/transform keys (use null to skip).
  • space: Number of spaces or a string (e.g., \t) for indentation.
  • Browser/Node.js Support: Works universally.
  • Performance: Avoid using this for very large objects in performance-critical code.

Shortcut for Logging

For quick debugging without generating a string:

console.log("%O", data); // Formatted output in supported environments

Leave a Reply

Your email address will not be published. Required fields are marked *