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.

Updated 2026-06-26

Overview

JSON (JavaScript Object Notation) is the dominant format for data exchange on the web — REST APIs, configuration files, log structures, and database exports all commonly use it. But raw JSON from an API or database dump is often compressed into a single line, making it nearly impossible to read or debug. Conversely, pretty-printed JSON in production payloads wastes bandwidth unnecessarily.

This guide covers the full formatting workflow: understanding JSON structure, identifying and fixing syntax errors, pretty-printing for readability, validating for correctness, and minifying for production use. Use the JSON Formatter for a one-click solution, or read on to understand the mechanics and common failure modes.

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: "hello". Single quotes are not valid.
  • number — integer or decimal: 42, 3.14, -7. No NaN or Infinity.
  • booleantrue or false (lowercase only).
  • null — represents an empty value.
  • object — nested {}.
  • array — nested [].

Structural rules:

  • Key-value pairs in an object are separated by commas.
  • The last pair in an object or array must NOT have a trailing comma.
  • Object keys must always be strings, always in double quotes.
  • There is no comment syntax in JSON.

Understanding these rules precisely lets you identify syntax errors by sight — the most common formatting problem is JSON that is valid JavaScript but invalid strict JSON.

Step 2: Identify Formatting Issues

Before formatting, scan for common problems that will cause a JSON parser to reject the input:

Trailing commas — the most frequent error. In JavaScript object literals and arrays, trailing commas after the last item are valid (and even encouraged by many style guides). In JSON, they are illegal.

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

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

Single quotes — JavaScript allows single-quoted strings. JSON does not. All strings and all keys must use double quotes.

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

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

Unquoted keys — JavaScript object literal syntax allows unquoted keys. JSON requires all keys to be double-quoted strings.

// Invalid JSON
{name: "Alice"}

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

Missing commas — forgetting a comma between two key-value pairs or between array elements.

Comments — JSON does not support // or /* */ comments. If your JSON source includes them, strip them before parsing or use a JSONC-aware parser.

Use the JSON Validator to get precise error messages with line and character positions pointing to each problem.

Step 3: Pretty-Print JSON

Pretty-printing adds indentation and line breaks to make the hierarchy of the data visually clear. This is essential when 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 produces 2-space indent, 4 produces 4-space indent. Passing a string like "\t" 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: jq . data.json.

For a one-click solution without any setup, paste your JSON into the JSON Formatter — it parses, validates, and pretty-prints in one step.

Choosing indentation size: 2 spaces is the most common choice in JavaScript, TypeScript, and Node.js projects. 4 spaces is common in Python and Java. Either is valid JSON — pick what is consistent with your project's existing conventions.

Step 4: Validate JSON

Formatting and validity are separate operations. A formatter will only succeed if the input is syntactically valid JSON. Validate first when you are unsure of the source data.

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

JSON.parse('your json here');

If valid, the parsed object is printed. If invalid, you get a SyntaxError with a message like Unexpected token } in JSON at position 47 — the position number tells you exactly where the parser failed.

Node.js command line:

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

If the file is valid JSON, the command exits silently. If invalid, an error is printed with the position of the failure.

Online validator: The JSON Validator highlights errors inline and gives human-readable descriptions of what is wrong and where — faster for complex files than reading raw parser error messages.

Step 5: Minify for Production

Minification removes all whitespace that is not part of a string value, producing the smallest possible valid JSON output. A 10 KB pretty-printed JSON file typically minifies to 3–5 KB — a 50–70% size reduction with no loss of data.

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 (no whitespace). For a single command that reads from stdin: echo '{ "name" : "Alice" }' | jq -c .

Use the JSON Minifier for 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. Minified JSON reduces payload transfer time and bandwidth costs. Never minify JSON that is 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. This is the single most common JSON error, especially from developers who primarily write JavaScript where trailing commas are permitted. A JSON linter or the JSON Validator will catch these before they reach a parser.

Single quotes. JSON strictly requires double quotes for both string values and object keys. Single quotes are valid JavaScript but invalid JSON. This error frequently appears when developers manually write JSON or copy object literals from JavaScript code.

Using comments. The JSON specification (ECMA-404) explicitly does not support comments. If you need comments in a JSON-like config format, evaluate JSON5, JSONC, or YAML depending on your use case. Stripping comments from JSONC before parsing can be done with //-aware preprocessors, but this is fragile if string values contain //.

Numeric keys. In JSON, all object keys must be strings. {1: "one"} is invalid JSON. The correct form is {"1": "one"}. This distinction matters particularly when converting data from languages where numeric dictionary keys are natural (Python, Ruby).

Assuming JSON.stringify output is always valid JSON. Functions, undefined values, and Symbol properties are silently dropped by JSON.stringify. A round-trip through JSON.stringifyJSON.parse can produce a different object than the original. Always inspect the serialised output when debugging serialisation issues.

Precision loss with large integers. JavaScript's number type handles integers exactly only up to 2^53 − 1 (9,007,199,254,740,991). Database IDs, timestamps, and other large integers that exceed this value should be transmitted 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

In practice, HTTP compression (gzip or Brotli) substantially reduces the size difference between pretty-printed and minified JSON in transit. However, minified JSON is still faster to parse (fewer characters for the tokeniser to process) and represents a smaller raw payload before compression.

For converting JSON to 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