How to Format JSON in JavaScript
Complete guide to pretty-printing and formatting JSON in JavaScript and Node.js using JSON.stringify.
Basic JSON Formatting with JSON.stringify
JavaScript's built-in JSON.stringify(value, replacer, space) formats JSON.
The third argument (space) controls indentation.
const data = { name: "Alice", age: 30, city: "Paris" };
// 2-space indentation (standard)
console.log(JSON.stringify(data, null, 2));
// 4-space indentation
console.log(JSON.stringify(data, null, 4));
// Tab indentation
console.log(JSON.stringify(data, null, "\t"));
Format a JSON String (parse then format)
const jsonString = '{"name":"Alice","age":30,"city":"Paris"}';
const data = JSON.parse(jsonString);
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
Format JSON in Node.js (read and write a file)
const fs = require('fs');
const raw = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(raw);
const formatted = JSON.stringify(data, null, 2);
fs.writeFileSync('data_formatted.json', formatted);
Format JSON for HTML Display
// Display formatted JSON in a element
const pre = document.getElementById('output');
pre.textContent = JSON.stringify(data, null, 2);
Format JSON from the Command Line (Node.js one-liner)
# Pipe JSON through Node.js
echo '{"name":"Alice","age":30}' | node -e "
let d=''; process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)));
"
# Or use jq (recommended for CLI)
echo '{"name":"Alice","age":30}' | jq '.'
What does JSON.stringify(data, null, 2) mean?
The three arguments are:
- data — the JavaScript object or array to serialize
- null — the replacer:
nullmeans include all properties; you can pass an array of key names to filter - 2 — the space: number of spaces per indent level, or a string like
"\t"for tabs
Need to format JSON without writing code?
Paste any JSON into the free online formatter — instant results, no JavaScript environment needed.
Open JSON Formatter →Frequently Asked Questions
What is the difference between JSON.stringify and JSON.parse?
JSON.stringify() converts a JavaScript object to a JSON string. JSON.parse() converts a JSON string into a JavaScript object. To format JSON, you typically parse it first then stringify with indentation.
Does JSON.stringify preserve key order?
Mostly, but not guaranteed by spec. In modern JS engines (V8, SpiderMonkey), integer keys come first in numeric order, then string keys in insertion order. If you need a guaranteed order, sort the keys manually before stringifying.
How do I format JSON in TypeScript?
Identically to JavaScript: JSON.stringify(data, null, 2). TypeScript adds type safety but the JSON API is the same. You can type the input as unknown or a specific interface.