pretty-print JSON using JavaScript
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Pretty-printing JSON in JavaScript usually means converting an object or JSON string into a human-readable, indented representation. The standard tool is JSON.stringify, but the right usage depends on whether you start with an object, a JSON string, or data that may contain circular references.
Basic pretty-print with JSON.stringify
For plain objects, the normal pattern is:
The third argument controls indentation. A value of 2 means two spaces per nesting level.
Output:
This is the most common answer and is usually enough for logs, debugging, and developer tools.
If the input is already a JSON string
If you receive raw JSON text, parse it first and then stringify it again with indentation.
If you call JSON.stringify directly on the string, JavaScript will just wrap it as a quoted string instead of formatting its internal JSON structure.
Use a replacer when you want custom output
The second argument to JSON.stringify can be a replacer function or an array of property names.
Example with selected keys:
Example with a replacer function:
That is useful when you want readable debug output without leaking sensitive fields.
Show pretty JSON in the browser
If you want to display formatted JSON in a page, use a pre element so whitespace is preserved.
Using textContent is important because it avoids treating the JSON as HTML.
Circular references need special handling
JSON.stringify throws an error if the object contains circular references.
A simple debug-safe replacer can skip repeated references:
This is helpful for diagnostics, though you should not treat it as a universal serialization strategy for production protocols.
Common Pitfalls
The most common mistake is calling JSON.stringify on a raw JSON string and expecting it to pretty-print the string's internal structure. Another is forgetting that JSON.stringify will throw on circular references. Developers also sometimes use innerHTML to display formatted JSON in the browser instead of textContent, which is unnecessary and potentially unsafe. Logging full objects without a replacer can also leak secrets such as tokens or password hashes. Finally, people often forget that pretty-printing is mainly for human readability and should usually be avoided in bandwidth-sensitive production payloads.
Summary
- Use
JSON.stringify(value, null, 2)to pretty-print ordinary JavaScript objects. - Parse JSON strings first, then stringify the parsed object with indentation.
- Use a replacer to filter or redact fields.
- Use
textContentwith apreelement when rendering formatted JSON in the browser. - Handle circular references explicitly if diagnostic objects may contain them.
- Treat pretty-printed JSON as a readability tool, not as a default wire format optimization.

