HomeArticlesHow ToFormat JSON
HOW TO

How to Format JSON Data

Learn how to format JSON data — pretty-printing with indentation, validating for errors, and minifying for production. Includes common error fixes.

Reviewed by the thecalcu.com team · Last updated August 4, 2026

Overview

JSON (JavaScript Object Notation) dominates data exchange on the web. REST APIs, configuration files, log structures, and database exports all lean on it. Raw JSON straight from an API or database dump is usually compressed onto a single line, which makes it nearly impossible to read or debug. Pretty-printed JSON in production payloads has the opposite problem: it wastes bandwidth for no reason.

This guide covers the full formatting workflow. That means understanding JSON structure, catching and fixing syntax errors, pretty-printing for readability, validating for correctness, and minifying for production. The JSON Formatter handles all of this in one click, or keep reading to understand the mechanics and where things typically break.

What You Need

  • The JSON data you want to format (from an API response, config file, or export)
  • A browser (for in-console validation) or the JSON Formatter tool
  • Basic familiarity with what JSON looks like

Step 1: Understand JSON Structure

JSON has exactly two container types and six total data types.

Container types:

  • Object: {}, an unordered collection of key-value pairs. Keys must be strings (double-quoted). Example: {"name": "Alice", "age": 30}
  • Array: [], an ordered list of values. Example: [1, 2, 3] or ["apple", "banana"]

Value types:

  • string: must use double quotes, like "hello". Single quotes aren't valid.
  • number: integer or decimal, like 42, 3.14, -7. No NaN or Infinity.
  • boolean: true or false (lowercase only).
  • null: represents an empty value.
  • object: nested {}.
  • array: nested [].

Structural rules:

  • Commas separate key-value pairs in an object.
  • The last pair in an object or array can't have a trailing comma.
  • Object keys are always strings, always in double quotes.
  • There's no comment syntax in JSON.

Knowing these rules cold lets you spot syntax errors on sight. The most common formatting problem out there is JSON that's valid JavaScript but invalid strict JSON.

Step 2: Identify Formatting Issues

Before formatting, scan for the problems that will get your JSON rejected by a parser.

Trailing commas show up more than anything else. JavaScript object literals and arrays allow a trailing comma after the last item, and plenty of style guides even encourage it. JSON doesn't allow it at all.

// Invalid JSON
{
  "name": "Alice",
  "age": 30,
}

// Valid JSON
{
  "name": "Alice",
  "age": 30
}

Single quotes work fine in JavaScript strings but not in JSON. Every string and every key needs double quotes.

// Invalid JSON
{'name': 'Alice'}

// Valid JSON
{"name": "Alice"}

Unquoted keys are legal JavaScript object literal syntax but not legal JSON. Every key needs to be a double-quoted string.

// Invalid JSON
{name: "Alice"}

// Valid JSON
{"name": "Alice"}

Missing commas between two key-value pairs or between array elements slip through easily when editing by hand.

Comments aren't supported at all, neither // nor /* */. Strip them out before parsing, or use a JSONC-aware parser if your source includes them.

The JSON Validator gives precise error messages with line and character positions pointing straight at each problem.

Step 3: Pretty-Print JSON

Pretty-printing adds indentation and line breaks so the hierarchy of the data reads clearly. It matters most when you're debugging API responses, reviewing config files, or diffing JSON in version control.

In JavaScript (browser console or Node.js):

// Parse the JSON string, then re-stringify with 2-space indentation
const parsed = JSON.parse(jsonString);
const pretty = JSON.stringify(parsed, null, 2);
console.log(pretty);

The third argument to JSON.stringify() controls indentation. 2 gives a 2-space indent, 4 gives a 4-space indent. Pass a string like "\t" and it indents with tabs.

With jq on the command line:

echo '{"name":"Alice","age":30}' | jq .

jq . pretty-prints with 2-space indentation and syntax-coloured output. For a file, run jq . data.json.

For a one-click option with no setup at all, paste your JSON into the JSON Formatter. It parses, validates, and pretty-prints in one pass.

Choosing indentation size: 2 spaces is the go-to in JavaScript, TypeScript, and Node.js projects. 4 spaces shows up more in Python and Java. Both count as valid JSON, so pick whatever matches your project's existing conventions.

Step 4: Validate JSON

Formatting and validity aren't the same operation. A formatter only succeeds if the input is syntactically valid JSON to begin with, so validate first when you're unsure of the source data.

Browser console (zero setup): Open DevTools (F12), go to the Console tab, and run:

JSON.parse('your json here');

Valid input prints the parsed object. Invalid input throws a SyntaxError with a message like Unexpected token } in JSON at position 47, and that position number tells you exactly where the parser gave up.

Node.js command line:

node -e "JSON.parse(require('fs').readFileSync('data.json', 'utf8'))"

A valid file makes the command exit silently. An invalid one prints an error along with the position of the failure.

Online validator: The JSON Validator highlights errors inline with human-readable descriptions of what's wrong and where, which is a lot faster than parsing raw error messages for complex files.

Step 5: Minify for Production

Minification strips out every bit of whitespace that isn't part of a string value, leaving the smallest valid JSON possible. A 10 KB pretty-printed file typically minifies down to 3 to 5 KB, a 50 to 70% size cut with zero data loss.

In JavaScript:

// JSON.stringify without the third argument produces minified output
const minified = JSON.stringify(JSON.parse(prettyJson));

With jq:

jq -c . data.json

The -c flag means compact output with no whitespace. From stdin: echo '{ "name" : "Alice" }' | jq -c .

The JSON Minifier does one-click minification without any command-line setup.

When to minify: Always minify JSON in production API responses and static data files served over the web, since it cuts payload transfer time and bandwidth costs. Never minify JSON stored in version control or committed to a repository. Pretty-printed JSON is far easier to diff and review in code review tools.

Common Mistakes to Avoid

Trailing commas are the single most common JSON error out there, especially among developers who write mostly JavaScript, where trailing commas are welcome. A JSON linter or the JSON Validator catches these before they reach a parser.

Single quotes trip people up constantly. JSON strictly requires double quotes for both string values and object keys, even though single quotes are perfectly valid JavaScript. This mistake shows up most when developers hand-write JSON or copy object literals straight from JavaScript code.

Using comments doesn't work, since ECMA-404 explicitly leaves them out of the spec. If you need comments in a JSON-like config format, look at JSON5, JSONC, or YAML depending on your use case. You can strip comments from JSONC with //-aware preprocessors, but that approach gets fragile fast if string values themselves contain //.

Numeric keys aren't valid in JSON. All object keys must be strings, so {1: "one"} is invalid and {"1": "one"} is the correct form. This distinction bites hardest when converting data from languages where numeric dictionary keys feel natural, Python and Ruby especially.

Assuming JSON.stringify output is always valid JSON causes quiet bugs. Functions, undefined values, and Symbol properties get silently dropped by JSON.stringify, so a round trip through JSON.stringify then JSON.parse can hand you back a different object than you started with. Inspect the serialised output directly when you're debugging serialisation issues.

Precision loss with large integers is easy to miss. JavaScript's number type only handles integers exactly up to 2^53 minus 1 (9,007,199,254,740,991). Database IDs, timestamps, and other large integers past that value should travel as strings in JSON to avoid silent rounding during parsing.

Formula & Methodology

JSON is standardised by ECMA-404 (the JSON Data Interchange Standard) and RFC 8259. Both documents are freely available and define the complete grammar for valid JSON.

Pretty-printing in JavaScript:

JSON.stringify(value, replacer, space)
// replacer: null (include all) or array of key names to include
// space: number of spaces (2 or 4) or a string (e.g. "\t")

Minifying in JavaScript:

JSON.stringify(JSON.parse(jsonString))
// Parsing then re-serialising removes all formatting

Size comparison example, same data:

  • Pretty-printed (2-space, 15 keys, 3 levels deep): ~820 bytes
  • Minified: ~380 bytes
  • Gzip-compressed minified: ~190 bytes

HTTP compression (gzip or Brotli) closes much of the size gap between pretty-printed and minified JSON once it's actually in transit. Even so, minified JSON parses faster since there are fewer characters for the tokeniser to chew through, and it starts out as a smaller raw payload before compression even kicks in.

To move JSON into other data formats, the JSON to CSV Formatter handles flat and nested JSON export to comma-separated values suitable for spreadsheet analysis.

Related Articles

COMPARISON

JSON vs YAML vs XML — Data Format Comparison

BEST OF

Best JSON Formatters Online 2026

COMPARISON

REST vs GraphQL — API Architecture Comparison

HOW TO

How to Convert a cURL Command to Python, JS, or Node

GUIDE

Developer Toolbox Guide — Essential Online Tools