ByteTips.

Guide

How to Format JSON in JavaScript

JSON.stringify does more than you think. Learn how to pretty-print, minify, validate, and sort JSON in plain JavaScript.

October 14, 2026 · 4 min read · Shayan

JSON is everywhere: API responses, config files, package.json, localStorage. And it usually arrives as one long, unreadable line. Formatting JSON means two things: checking that it is valid, and printing it in a shape humans can read. JavaScript gives you everything you need for both, built in.

The one-liner: JSON.stringify with spacing

JSON.stringify takes three arguments: the value, a replacer, and a space argument. Pass 2 as the third argument and you get clean, indented output. This is the line you will use most often:

const data = { name: "Ada", languages: ["JavaScript", "Rust"], active: true };

console.log(JSON.stringify(data, null, 2));
// {
//   "name": "Ada",
//   "languages": [
//     "JavaScript",
//     "Rust"
//   ],
//   "active": true
// }

The second argument, null here, is a replacer function or array that filters which keys get included. Passing null keeps everything. The third argument controls indentation: a number means that many spaces, while a string like "\t" indents with tabs instead.

Formatting a JSON string you already have

Often you do not have an object, you have a string: the raw body of a fetch response, or text pasted from a log. Formatting that takes two steps: parse it, then stringify it again with spacing. Always wrap the parse in try/catch, because JSON.parse throws on invalid input:

function formatJSON(str, indent = 2) {
  try {
    return JSON.stringify(JSON.parse(str), null, indent);
  } catch (err) {
    throw new Error("Invalid JSON: " + err.message);
  }
}

console.log(formatJSON('{"b":2,"a":1}'));
// {
//   "b": 2,
//   "a": 1
// }

One detail worth knowing: JSON.parse does not preserve key order guarantees for integer-like keys, which JavaScript engines sort numerically. For display purposes this rarely matters, but do not rely on key order for logic.

The four errors that break JSON

When JSON.parse throws, the cause is almost always one of these. JavaScript object literals allow all of them; JSON allows none of them:

  • Trailing commas — {"a": 1,} is invalid. JSON forbids a comma after the last item.
  • Single quotes — JSON requires double quotes around every key and string.
  • Unquoted keys — {name: "Ada"} is valid JavaScript but not valid JSON.
  • Comments — JSON has no comment syntax. A // line inside JSON breaks the parser.

The error message tells you the character position where parsing failed. If you are staring at a large payload, paste it into a validator that points at the exact line instead of hunting by eye.

Minifying and sorting keys

Going the other direction, call JSON.stringify with no spacing argument to get the most compact form. That is what you want before storing JSON in a URL, a cookie, or a database field where every byte counts:

const pretty = '{\n  "a": 1,\n  "b": 2\n}';
const minified = JSON.stringify(JSON.parse(pretty));
console.log(minified); // {"a":1,"b":2}

If you diff JSON files in version control, sorted keys make the diff readable. Pass a replacer array of sorted keys, or sort the object yourself before stringifying. In real projects, most JSON formatting happens in two places: your editor, where a formatter extension keeps config files tidy, and your debugging workflow, where you format API responses to actually read them. Both use exactly the techniques above. For a quick one-off check, you do not need any of this code at all.

Try it

Paste any JSON into the JSON Formatter to validate, beautify, or minify it instantly in your browser, with nothing uploaded. If you need the same data in another shape, the JSON / YAML / CSV converter converts it to YAML or CSV in one click. And if the JSON you are formatting came from an API token, read What Is a JWT? How to Decode One Safely next — JWT payloads are JSON, and the same formatting skills apply.

More guides