What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that has become the de facto standard for transmitting data between servers and web applications. Originally derived from JavaScript object syntax, JSON is language-independent and supported by virtually every modern programming language. Whether you're building a REST API, storing configuration files, or passing data between microservices, chances are you're working with JSON every day.
A typical JSON document consists of key-value pairs organized into objects (delimited by curly braces) and ordered lists of values called arrays (delimited by square brackets). Values can be strings, numbers, booleans, null, objects, or arrays — and they can be nested to arbitrary depth.
{
"name": "DuskTools",
"version": "2.1.0",
"features": ["json-formatter", "base64-codec", "regex-tester"],
"config": {
"theme": "dark",
"autoSave": true,
"maxFileSize": null
}
}The example above is already formatted — each nested level is indented by two spaces, making the hierarchy immediately obvious. But JSON received from APIs, log files, or database exports is often a single compressed line, which is where formatting comes in.
Why Formatting JSON Matters
Unformatted (minified) JSON is compact and efficient for machines, but nearly impossible for humans to read. Consider this single-line response from an API:
{"users":[{"id":1,"name":"Alice","roles":["admin","editor"],"prefs":{"theme":"dark","lang":"en"}},{"id":2,"name":"Bob","roles":["viewer"],"prefs":{"theme":"light","lang":"fr"}}],"total":2,"page":1}Good luck spotting a missing value or verifying the nesting structure in that blob. Formatting (also called "pretty-printing" or "beautifying") adds consistent whitespace and line breaks so you can:
- Debug faster — identify missing commas, extra brackets, or wrong data types at a glance.
- Collaborate more easily — formatted JSON produces meaningful diffs in version control, making code reviews cleaner.
- Document APIs — readable examples in documentation help consumers understand your data model without writing extra prose.
- Reduce cognitive load — scanning a well-indented tree is orders of magnitude faster than parsing a wall of text mentally.
JSON Syntax Rules You Must Know
Before you can format JSON, you need to know what makes it valid. Subtle syntax mistakes are the number one reason JSON formatting tools fail with cryptic errors.
Keys Must Be Double-Quoted Strings
Unlike JavaScript object literals, JSON requires every key to be wrapped in double quotes. Single quotes and unquoted keys are invalid:
// ❌ Invalid JSON
{ name: "Alice", 'age': 30 }
// ✅ Valid JSON
{ "name": "Alice", "age": 30 }No Trailing Commas
A trailing comma after the last element in an object or array is the most common JSON error developers encounter. Many programming languages allow trailing commas, but JSON does not:
// ❌ Invalid — trailing comma
{ "name": "Alice", "age": 30, }
// ✅ Valid
{ "name": "Alice", "age": 30 }Strings Must Use Double Quotes
String values must be enclosed in double quotes. Single quotes, backticks, and unquoted strings are all invalid in JSON.
No Comments
The JSON specification does not support comments. If you need annotated configuration files, consider JSON5, JSONC (used by VS Code), YAML, or TOML instead.
Valid Value Types Only
JSON supports exactly six value types: string, number, boolean (true/false), null, object, and array. Values like undefined, NaN, Infinity, functions, and dates are not valid JSON.
How to Format JSON Manually
While you rarely need to format JSON by hand, understanding the mechanics helps you reason about tooling and catch errors:
- Start at the outermost brace or bracket. Place it on its own line.
- For each nested level, add consistent indentation (typically 2 or 4 spaces, or one tab).
- Place each key-value pair on its own line. Put a space after the colon separator.
- Place each array element on its own line if the array contains objects or is long; short primitive arrays can stay on one line.
- Ensure closing braces/brackets align with the indentation of the line that opened them.
Here is the same API response from earlier, formatted with 2-space indentation:
{
"users": [
{
"id": 1,
"name": "Alice",
"roles": ["admin", "editor"],
"prefs": {
"theme": "dark",
"lang": "en"
}
},
{
"id": 2,
"name": "Bob",
"roles": ["viewer"],
"prefs": {
"theme": "light",
"lang": "fr"
}
}
],
"total": 2,
"page": 1
}Formatting JSON with Code
Every major language includes built-in JSON formatting. Here are the most common approaches:
JavaScript / Node.js
const data = { name: "Alice", scores: [95, 87, 92] };
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);The third argument to JSON.stringify controls indentation. Pass 2 for two spaces, 4 for four, or "\\t" for tabs.
Python
import json
data = {"name": "Alice", "scores": [95, 87, 92]}
formatted = json.dumps(data, indent=2, sort_keys=True)
print(formatted)The sort_keys=True option alphabetizes keys, which helps produce consistent diffs.
Command Line with jq
# Pretty-print a JSON file
cat data.json | jq .
# Pretty-print with 4-space indent
cat data.json | jq --indent 4 .
# Extract a specific field
cat data.json | jq '.users[0].name'jq is one of the most powerful command-line JSON processors. It formats by default and can filter, transform, and query JSON data.
Using an Online JSON Formatter
When you need to quickly inspect or clean up JSON without opening a code editor, an online formatter is the fastest option. Our JSON Formatter lets you paste raw JSON and instantly get a formatted, syntax-highlighted result. It also validates your JSON and highlights the exact line and character position of any errors.
Benefits of using an online tool:
- No installation or setup required — works in any browser.
- Instant error detection with clear messages (e.g., "Unexpected token at line 14, column 23").
- Toggle between 2-space, 4-space, and tab indentation with one click.
- Copy the formatted result or download it as a file.
- Switch between tree view and text view for exploring deeply nested structures.
If you frequently work with JSON API responses, keep a formatter bookmarked — it will save you hours over the course of a project.
Common JSON Errors and How to Fix Them
Unexpected Token Errors
This usually means a trailing comma, a missing comma between elements, or an unquoted key. Paste the JSON into a validator and look at the reported line number. The error is almost always on or just before that line.
Unexpected End of Input
This means you have unbalanced braces or brackets. Count your opening and closing delimiters — they must match exactly. Most code editors can highlight matching brackets to help you find the mismatch.
Invalid Unicode Escape Sequences
JSON allows Unicode escapes like \u0041 (the letter A), but malformed sequences like \u00 or \uXYZW will cause parse errors.
Number Format Issues
JSON numbers cannot have leading zeros (except 0 itself), cannot use hex notation (0xFF), and cannot include NaN or Infinity. If you need to represent these values, encode them as strings.
JSON in APIs: Request and Response Formatting
When working with REST APIs, you'll encounter JSON in both request bodies and responses. A few tips for handling JSON in API workflows:
- Always set the Content-Type header to
application/jsonwhen sending JSON request bodies. - Parse before accessing — in JavaScript, use
response.json()(which returns a promise) rather than trying to access properties on the raw response body. - Handle parsing errors gracefully — wrap
JSON.parse()in a try/catch block. Malformed responses from upstream services are more common than you think. - Use a JSON Path finder to navigate complex API responses. Our JSON Path Finder lets you click on any value and get its access path instantly.
// Safe JSON parsing in JavaScript
function safeParse(raw) {
try {
return { data: JSON.parse(raw), error: null };
} catch (err) {
return { data: null, error: err.message };
}
}Minification vs Beautification
Formatting and minification are opposite operations, and both have their place:
- Beautification (pretty-printing) adds whitespace for readability. Use it during development, debugging, documentation, and code review.
- Minification strips all unnecessary whitespace to reduce payload size. Use it in production API responses, stored data, and anywhere bandwidth or storage costs matter.
To minify JSON in JavaScript, simply call JSON.stringify(data) without the third argument. In Python, use json.dumps(data, separators=(",", ":")) to eliminate all extra whitespace.
For a typical API response, the difference can be significant. A formatted JSON payload of 10 KB might compress down to 6 KB when minified — a 40% reduction before gzip compression is even applied.
Validating JSON
Formatting a document only works if the JSON is valid to begin with. If your formatter throws an error, you need to validate and fix the raw input first. Here is a quick validation checklist:
- All keys are double-quoted strings.
- All string values use double quotes (not single quotes).
- No trailing commas after the last element.
- All braces and brackets are balanced.
- No comments are present.
- Numbers are valid (no leading zeros, no hex, no
NaN). - No JavaScript-specific values (
undefined, functions).
Paste your JSON into DuskTools' JSON Formatter and it will highlight the exact position of any syntax errors, along with a human-readable explanation of what went wrong.
Converting JSON to Other Formats
Formatted JSON is often a stepping stone to other workflows. Once your JSON is clean and validated, you might want to:
- Generate TypeScript interfaces — use our JSON to TypeScript converter to create type-safe interfaces from any JSON payload. This is invaluable when integrating with third-party APIs.
- Extract nested values — the JSON Path Finder helps you build the access path for deeply nested fields without counting bracket levels by hand.
- Convert to CSV or YAML — for data analysis or configuration management, exporting JSON to a tabular or human-friendly format can streamline your workflow.
Tips for Working with JSON Daily
The best developers don't memorize JSON rules — they use tools that enforce them automatically.
- Configure your editor — enable format-on-save for JSON files in VS Code with
"editor.formatOnSave": trueand install a JSON language extension. - Use a linter — tools like
jsonlintcatch errors before they reach production. - Pretty-print in the terminal — pipe API responses through
jq .orpython -m json.toolfor instant formatting. - Bookmark a web-based formatter — when you're on a machine without your usual tools, an online JSON Formatter is one click away.
- Validate before committing — add a pre-commit hook that runs
jq . config.json > /dev/nullto catch broken JSON files before they enter your repository.
Wrapping Up
JSON formatting is a small skill with outsized impact on your daily productivity. Whether you use JSON.stringify in code, jq in the terminal, or a web-based tool like our JSON Formatter, the important thing is to always work with readable, validated JSON. You'll debug faster, collaborate more smoothly, and spend less time chasing phantom syntax errors.