How to Format JSON in JavaScript
Unformatted JSON is hard to read and debug. Here is how to format JSON properly in JavaScript and online tools that make it instant.
Format JSON instantly
Use our free JSON Formatter — paste your JSON and get a formatted output in one click.
Using JSON.stringify in JavaScript
The built-in JSON.stringify() method converts a JavaScript object to a JSON string. The third parameter controls indentation.
const data = { name: "DevUtils", version: 2, active: true };
// Unformatted
JSON.stringify(data);
// {"name":"DevUtils","version":2,"active":true}
// Formatted with 2 spaces
JSON.stringify(data, null, 2);
// {
// "name": "DevUtils",
// "version": 2,
// "active": true
// }Format JSON with 4 spaces
JSON.stringify(data, null, 4);
Change the third argument to any number to control indentation. Most style guides recommend 2 or 4 spaces.
Format JSON using tabs
JSON.stringify(data, null, " ");
Parse and format a JSON string
If you have a JSON string and want to format it, parse it first then stringify it back.
const jsonString = '{"name":"DevUtils","version":2}';
const parsed = JSON.parse(jsonString);
const formatted = JSON.stringify(parsed, null, 2);
console.log(formatted);Format JSON in Node.js
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
fs.writeFileSync('data-formatted.json', JSON.stringify(data, null, 2));Common formatting mistakes
Trailing commas
JSON does not allow trailing commas — remove them before formatting
Single quotes
JSON requires double quotes for all keys and string values
Undefined values
JSON.stringify removes keys with undefined values silently