Home›Articles›How To›Format 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.

Written by · Reviewed by the thecalcu.com team · Published June 26, 2026 · 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.

Frequently Asked Questions

What is JSON and what is it used for?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format defined by ECMA-404 and RFC 8259. It transmits structured data between a server and a client, between microservices, and inside configuration files. JSON is language-independent but borrows conventions familiar from JavaScript, and it's natively parsed by virtually every programming language, which is why it's become the default data format for REST APIs, web application configs, and developer tooling.

What is the difference between pretty-printed and minified JSON?

Pretty-printed JSON uses indentation (typically 2 or 4 spaces), line breaks after each key-value pair, and consistent spacing so the structure reads clearly. Minified JSON strips out all whitespace that isn't part of a string value, producing compact output that's harder to read but smaller in file size. A JSON file that's 10 KB pretty-printed might compress to 3 to 5 KB minified. Development and debugging call for pretty-printing; production API responses and file delivery call for minification.

What are the most common JSON syntax errors?

Four errors show up again and again: trailing commas after the last item in an object or array (valid in JavaScript, illegal in JSON), single quotes used instead of double quotes for strings or keys, unquoted object keys (fine in JavaScript object literals, not fine in JSON), and missing commas between consecutive key-value pairs or array elements. These same four errors are usually why JSON that looks correct in a JavaScript context fails to parse as strict JSON.

Does JSON support comments?

It doesn't. The JSON specification (ECMA-404) explicitly leaves comments out. Paste JSON with // or /* */ comments into a JSON parser and it throws a syntax error. That's a deliberate design choice: JSON is meant as a minimal data interchange format, not a configuration language. If you need comments in a JSON-like config file, reach for JSON5 (a superset that allows comments and trailing commas) or YAML instead. Projects like VS Code use JSONC (JSON with Comments), which needs its own specific parser.

How do I validate JSON in a browser without any tools?

Open your browser's developer console (F12 to Console) and run JSON.parse(yourJsonString). Valid JSON returns the parsed object. Invalid JSON throws a SyntaxError with a message pointing at the problem, something like 'Unexpected token , in JSON at position 45'. It's the fastest way to check validity without installing anything. For repeated checks or large files, an online JSON validator gives you better error messages and line-by-line highlighting.

What indentation size is standard for JSON?

There isn't a universal standard. The JSON specification itself says nothing about indentation. In practice, 2-space indentation dominates in JavaScript and Node.js ecosystems (it's the JSON.stringify() default, and what Prettier and most npm packages use). 4-space indentation shows up more in Python (json.dumps(indent=4)) and some enterprise Java environments. Either works; pick whatever matches your project's existing style guide. Tabs rarely get used for JSON indentation in shared codebases.

How do I pretty-print JSON in JavaScript?

Use JSON.stringify(value, null, indent), where the third argument sets the number of spaces for indentation. JSON.stringify(obj, null, 2) gives you 2-space indented JSON, and JSON.stringify(obj, null, 4) gives you 4-space. The second argument (null here) is an optional replacer function or array that filters which keys to include; pass null to include everything. To minify in JavaScript, call JSON.stringify(obj) with no third argument, which produces compact output with no extra whitespace.

What data types are valid in JSON?

Exactly six: string (double-quoted only), number (integer or decimal, no NaN or Infinity), boolean (true or false, lowercase), null, object ({} holding key-value pairs where keys are strings), and array ([] holding ordered values of any valid JSON type). JSON has no room for undefined, functions, Date objects (dates need to be serialised as strings), BigInt, or Symbol. Trying to serialise these with JSON.stringify() either drops them silently or throws an error.

Why does JSON.stringify() drop some properties?

JSON.stringify() silently skips properties whose values are undefined, functions, or Symbol. If an object has a property set to undefined, that property just doesn't show up in the JSON output at all. This trips people up when serialising data from a JavaScript runtime to send over an API: properties that exist in memory can vanish from the serialised payload. Use explicit null values instead of undefined for any property you want to keep with an empty value.

How do I handle large JSON files?

In-browser online formatters can struggle above a few megabytes because of memory constraints. Command-line tools handle large files far better. jq is the industry standard for filtering, formatting, and transforming JSON from the command line, and the command jq . large-file.json pretty-prints the entire file with 2-space indentation. For truly massive files, hundreds of megabytes, streaming JSON parsers in Python or Node.js process the data incrementally instead of loading it all into memory at once.

Can I convert JSON to other formats?

You can convert it to CSV for spreadsheet analysis, XML for systems that require XML input, YAML for human-readable configuration, and more. Converting to CSV works best when the JSON is a flat array of objects with consistent keys, since each object becomes a row and each key becomes a column header. Nested objects need flattening first. The [JSON to CSV Formatter](/json-to-csv-formatter/) handles this conversion automatically, or use jq on the command line if you're scripting it.

What is the maximum size or nesting depth allowed in JSON?

The specification itself sets no limits on nesting depth, string length, or number precision. Practical limits come from parsers and environments instead. Most production JSON parsers, browser engines, Node.js, Python's json module, handle arbitrary nesting depth up to whatever stack or memory limit is available. JavaScript's number type (an IEEE 754 double-precision float) represents integers exactly only up to 2^53 minus 1 (9,007,199,254,740,991). Send larger integers as strings in JSON to avoid losing precision during parsing.

Related Articles

COMPARISON

JSON vs YAML vs XML — Data Format Comparison

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

About the author