coding
JSON
javascript

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:

javascript
1const data = {
2  name: "Ava",
3  age: 30,
4  skills: ["JavaScript", "Node.js", "SQL"],
5};
6
7const pretty = JSON.stringify(data, null, 2);
8console.log(pretty);

The third argument controls indentation. A value of 2 means two spaces per nesting level.

Output:

json
1{
2  "name": "Ava",
3  "age": 30,
4  "skills": [
5    "JavaScript",
6    "Node.js",
7    "SQL"
8  ]
9}

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.

javascript
1const raw = '{"status":"ok","count":3,"items":[1,2,3]}';
2
3const parsed = JSON.parse(raw);
4const pretty = JSON.stringify(parsed, null, 2);
5
6console.log(pretty);

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:

javascript
1const user = {
2  id: 42,
3  name: "Ava",
4  passwordHash: "secret",
5  role: "admin",
6};
7
8const safe = JSON.stringify(user, ["id", "name", "role"], 2);
9console.log(safe);

Example with a replacer function:

javascript
1const payload = {
2  id: 42,
3  passwordHash: "secret",
4  active: true,
5};
6
7const pretty = JSON.stringify(payload, (key, value) => {
8  if (key === "passwordHash") {
9    return "[redacted]";
10  }
11  return value;
12}, 2);
13
14console.log(pretty);

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.

html
1<pre id="output"></pre>
2<script>
3  const data = { env: "prod", version: 3, features: ["search", "billing"] };
4  document.getElementById("output").textContent = JSON.stringify(data, null, 2);
5</script>

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.

javascript
1const obj = {};
2obj.self = obj;
3
4// JSON.stringify(obj) throws

A simple debug-safe replacer can skip repeated references:

javascript
1function safeStringify(value, space = 2) {
2  const seen = new WeakSet();
3
4  return JSON.stringify(value, (key, val) => {
5    if (typeof val === "object" && val !== null) {
6      if (seen.has(val)) {
7        return "[circular]";
8      }
9      seen.add(val);
10    }
11    return val;
12  }, space);
13}
14
15const obj = {};
16obj.self = obj;
17console.log(safeStringify(obj));

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 textContent with a pre element 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.

Course illustration
Course illustration

All Rights Reserved.