How to pretty print JSON in JavaScript

Pretty printing JSON in JavaScript is simple, but it is one of the most useful tricks for debugging nested data, logging responses, and documenting API payloads.

The basic approach

const output = JSON.stringify(data, null, 2);

The third argument controls indentation. A value of 2 is a common choice because it is readable without becoming too wide.

Example

const data = { user: { id: 42, name: "Ada" } };
console.log(JSON.stringify(data, null, 2));
{
  "user": {
    "id": 42,
    "name": "Ada"
  }
}

Common pitfall

If the input is a JSON string instead of an object, parse it first with JSON.parse. If the string is invalid, fix the syntax before trying to pretty print it.

FAQ

What does the third argument to JSON.stringify do?

It controls indentation in the output.

Can I pretty print a JSON string directly?

Only after parsing it into a JavaScript value with JSON.parse.

Why use pretty printing in logs?

It makes nested responses much easier to inspect while debugging.

Can I do this without code?

Yes. Use MyJSONTool’s formatter pages if you just want the output quickly.