← Home · Blog

How to Format JSON — A Complete Beginner's Guide

Published: May 20, 2025 · Last updated: June 20, 2025 · 12 min read

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data between servers, web applications, and APIs. Despite its name, JSON is language-independent and used by virtually every programming language including Python, Java, C#, Go, Ruby, PHP, Swift, and Kotlin.

A JSON document consists of two structures: objects (key-value pairs wrapped in curly braces {}) and arrays (ordered lists wrapped in square brackets []). Values can be strings, numbers, booleans, null, objects, or arrays — allowing deeply nested data structures of arbitrary complexity.

Why Format JSON?

When APIs return JSON data, it's often delivered in a compact, single-line format to minimize bandwidth:

{"name":"John","age":30,"address":{"city":"New York","zip":"10001"},"skills":["JavaScript","Python","Go"],"projects":[{"name":"API","status":"active"},{"name":"Dashboard","status":"completed"}]}

While machines read this perfectly, humans struggle to understand the structure. JSON formatting (also called pretty-printing) adds indentation and line breaks to make the data readable:

{ "name": "John", "age": 30, "address": { "city": "New York", "zip": "10001" }, "skills": ["JavaScript", "Python", "Go"], "projects": [ {"name": "API", "status": "active"}, {"name": "Dashboard", "status": "completed"} ] }

Now you can instantly see the nesting structure, identify keys, understand the data hierarchy, and spot errors. Formatting is essential during development, debugging, and documentation — but the compact form is better for production data transfer.

Indentation Standards: 2-Space vs 4-Space vs Tabs

There's no universally mandated indentation standard for JSON, but conventions have emerged in different communities:

StyleCommon UsageProsCons
2 spacesJavaScript/Node.js ecosystem, npm packages, Google style guideCompact, fits more content on screen, most common in web developmentHarder to see deep nesting at a glance
4 spacesPython ecosystem, Java, enterprise environmentsClear visual hierarchy, easier to read deep structuresUses more horizontal space
TabsGo, some C/C++ projectsConfigurable width per user, smaller file sizeInconsistent rendering across tools, less common for JSON

Recommendation: Use 2-space indentation for JSON in web development projects. It's the default in most JavaScript formatters and matches what developers expect from npm packages, TypeScript configs, and modern APIs. For Python projects, 4-space indentation aligns with PEP 8 conventions.

JSON Formatting vs Minifying

Formatting (pretty-printing) makes JSON readable by adding whitespace. Minifying does the opposite — removes all unnecessary whitespace to reduce file size.

Minification Benefits Quantified

Here's the actual size difference for a typical API response:

FormatSizeReduction
Formatted (2-space)2,048 bytes—
Formatted (4-space)2,560 bytes+25%
Minified1,433 bytes-30%
Minified + gzip~450 bytes-78%

For production APIs serving millions of requests, minification provides meaningful bandwidth savings and faster parse times. Modern HTTP compression (gzip/Brotli) works on top of minification for even better results.

When to Minify vs Format — Decision Guide

ScenarioUse FormattedUse Minified
Development/debugging✅
Config files in repos✅
API documentation examples✅
Production API responses✅
Data stored in databases✅
Log files✅ (one line per entry)
Mobile app payloads✅
Webhook payloads✅
Data exports for users✅ (option for both)

How to Format JSON (Multiple Methods)

Method 1: Online Tools (Fastest)

The quickest way is to use an online formatter like JSON Suite's Formatter:

  1. Paste your JSON into the input editor
  2. Click "Format" — instant result with syntax highlighting
  3. Copy or download the formatted output

This is ideal for quick debugging, API response inspection, or when you don't want to install anything. Your data stays in your browser and is never sent to a server.

Method 2: Command Line Tools

If you work in the terminal, several tools are available:

jq — The standard for JSON processing:

# Format JSON file jq . data.json # Format with 4-space indent jq --indent 4 . data.json # Minify jq -c . data.json # Format output from curl curl https://api.example.com/data | jq . # Install: brew install jq (Mac) | apt install jq (Linux)

Python's json.tool — Built-in, no installation needed:

# Format JSON file python -m json.tool data.json # Format with custom indent python -m json.tool --indent 4 data.json # Minify (Python 3.9+) python -m json.tool --compact data.json # Pipe from other commands curl https://api.example.com/data | python -m json.tool

Node.js — One-liner for JS developers:

# Format with 2-space indent node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('data.json','utf8')),null,2))" # Using npx with a formatter package npx json-format data.json

Method 3: IDE Extensions

Most code editors format JSON with a keyboard shortcut:

  • VS Code: Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac)
  • JetBrains IDEs: Ctrl+Alt+L (Windows/Linux) or Cmd+Option+L (Mac)
  • Sublime Text: Install "Pretty JSON" package, then Ctrl+Shift+P → "Pretty JSON: Format"
  • Vim: :%!jq . or :%!python -m json.tool

Formatting Tools Comparison

ToolTypeProsCons
JSON SuiteOnlineFree, no install, syntax highlighting, validation, works offlineRequires browser
jqCLIPowerful queries, fast, scriptableLearning curve for complex queries
Python json.toolCLIBuilt-in, no install neededLimited options
VS CodeIDEIntegrated, schema validation, auto-completeRequires VS Code installation
PrettierCLI/IDEConsistent style, supports many formatsRequires Node.js
JSON Viewer (Chrome)Browser extAuto-formats API responsesChrome only, limited editing

JSON Pretty-Print in Different Languages

Here's how to format JSON programmatically in popular languages:

JavaScript / Node.js

// Format with 2-space indent const formatted = JSON.stringify(data, null, 2); // Format with 4-space indent const formatted = JSON.stringify(data, null, 4); // Format with tabs const formatted = JSON.stringify(data, null, '\t'); // Minify (compact) const minified = JSON.stringify(data); // Custom formatting with replacer const formatted = JSON.stringify(data, (key, value) => { // Transform or filter values return value; }, 2);

Python

import json data = {"name": "Alice", "age": 30} # Format with 2-space indent formatted = json.dumps(data, indent=2) # Format with 4-space indent (Python default for json.tool) formatted = json.dumps(data, indent=4) # Format with sorted keys formatted = json.dumps(data, indent=2, sort_keys=True) # Minify minified = json.dumps(data, separators=(',', ':')) # Ensure ASCII (escape non-ASCII characters) formatted = json.dumps(data, indent=2, ensure_ascii=True) # Pretty-print to file with open('output.json', 'w') as f: json.dump(data, f, indent=2)

Go

package main import ( "encoding/json" "fmt" ) func main() { data := map[string]interface{}{ "name": "Alice", "age": 30, } // Format with 2-space indent formatted, _ := json.MarshalIndent(data, "", " ") fmt.Println(string(formatted)) // Minify minified, _ := json.Marshal(data) fmt.Println(string(minified)) }

Java

// Using Jackson import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; ObjectMapper mapper = new ObjectMapper(); // Enable pretty-printing mapper.enable(SerializationFeature.INDENT_OUTPUT); String formatted = mapper.writeValueAsString(data); // Using Gson import com.google.gson.Gson; import com.google.gson.GsonBuilder; Gson gson = new GsonBuilder().setPrettyPrinting().create(); String formatted = gson.toJson(data);

C#

using System.Text.Json; var data = new { Name = "Alice", Age = 30 }; // Format with indentation var options = new JsonSerializerOptions { WriteIndented = true }; string formatted = JsonSerializer.Serialize(data, options); // Minify (default) string minified = JsonSerializer.Serialize(data); // Using Newtonsoft.Json using Newtonsoft.Json; string formatted = JsonConvert.SerializeObject(data, Formatting.Indented); string minified = JsonConvert.SerializeObject(data, Formatting.None);

PHP

$data = ['name' => 'Alice', 'age' => 30]; // Format with indentation (PHP 5.4+) $formatted = json_encode($data, JSON_PRETTY_PRINT); // Minify (default) $minified = json_encode($data); // With multiple flags $formatted = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );

JSON Validation

Validation checks whether your JSON follows correct syntax rules. Common errors include:

  • Missing commas between key-value pairs
  • Using single quotes instead of double quotes
  • Trailing commas after the last item
  • Unquoted property names
  • Missing closing brackets or braces
  • Invalid escape sequences in strings
  • Comments (not allowed in standard JSON)

A good formatter will not only format valid JSON but also report exactly where an error occurs — showing the line number and character position. Our JSON Formatter & Validator highlights the exact error location in the editor with a descriptive message.

Best Practices for JSON Formatting

  • Always validate JSON before sending it to an API
  • Use 2-space indentation (industry standard for web development)
  • Keep keys consistent — use camelCase or snake_case throughout a project, not both
  • Minify JSON in production API responses to save bandwidth
  • Format JSON config files for version control readability
  • Use a JSON formatter with syntax highlighting for debugging
  • Never store sensitive data in JSON that gets logged or cached
  • Use schema validation (JSON Schema) for complex data structures
  • Enable auto-format on save in your IDE for consistent styling
  • Consider sort-keys options for deterministic output (helps with diffs)

Try It Now

Ready to format your JSON? Use our free JSON Formatter & Validator — paste your data, click Format, and get instant results. Features include:

  • Syntax highlighting with color-coded keys, strings, numbers, and booleans
  • Instant validation with detailed error messages
  • One-click minification
  • Copy or download formatted output
  • Keyboard shortcuts for power users
  • Dark mode support

No sign-up required, and your data never leaves your browser for complete privacy.

More Articles

JSON vs XML vs YAML — When to Use Which Format

10+ Common JSON Errors and How to Fix Them

JSON Schema Explained

What is JSON — A Complete Guide for Beginners