JSON.stringify() Pretty Print Examples

Learn how to pretty print JSON with JSON.stringify(), indentation, and replacer options for readable objects and arrays.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JSON.stringify() Pretty Print Examples

JSON.stringify() turns JavaScript values into JSON text, and the indentation argument makes the output easy to read. That pretty-print form is useful when you want clean logs, human-readable files, or examples for debugging.

The same method is also useful when you want to compare the shape of objects or arrays before sending them to an API. If you later need the reverse step, JSON.parse is the natural companion article.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Pretty print an object with JSON.stringify()

The indentation argument controls how much space each nesting level gets.

javascript
const object = {
  name: "Jane Doe",
  nickname: "Lorem Ipsum",
  likesCoding: true,
};

console.log("pretty-object:\n" + JSON.stringify(object, null, 2));
Output

You should see 6 lines, in order: pretty-object:, {, "name": "Jane Doe",, "nickname": "Lorem Ipsum",, "likesCoding": true, }.

Use this when you want a readable JSON object for logs, examples, or docs.


Method 2: Pretty print an array with tabs

You can pass a string such as to indent nested output with tabs.

javascript
const array = [1, 2, 3];

console.log("pretty-array:\n" + JSON.stringify(array, null, "\t"));
Output

You should see 6 lines, in order: pretty-array:, [, 1,, 2,, 3, ].

This is useful when you want compact but readable array output.


Method 3: Use replacer and indentation together

The replacer can filter or transform values before the final JSON string is produced.

javascript
const user = { name: "Ana", role: "admin", active: true };
const pretty = JSON.stringify(user, ["name", "active"], 2);

console.log("pretty-filtered:\n" + pretty);
Output

You should see 5 lines, in order: pretty-filtered:, {, "name": "Ana",, "active": true, }.

Use this when you want a readable JSON sample and you only want to expose selected fields.


Summary

JSON.stringify() pretty printing is the easiest way to turn objects and arrays into readable JSON text. Use the indentation argument for formatting, and use a replacer when you want to filter or reshape the output before writing it to a file or showing it on screen.


Official documentation

Steve Alila

Specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, …