DevToolBoxKOSTENLOS
Blog

JSON Formatter: Der komplette Leitfaden zum Formatieren und Verschoenern von JSON (2026)

14 Min. Lesezeitvon DevToolBox

TL;DR

A JSON formatter (also called a JSON beautifier or JSON prettifier) transforms compact, minified JSON into human-readable, indented text. Whether you are debugging an API response, reviewing a config file, or collaborating with teammates, formatted JSON saves time and prevents errors. You can format JSON in your browser with our free JSON formatter online, in VS Code with a single shortcut, on the command line with jq, or programmatically in JavaScript and Python. This guide covers every method, plus validation, minification, viewers, common errors, and a comparison of JSON vs YAML vs TOML.

Key Takeaways

  • JSON formatting adds indentation and line breaks so that nested objects and arrays are immediately visible.
  • Use a JSON formatter online for quick, zero-install formatting and validation in the browser.
  • VS Code formats JSON with Shift+Alt+F (Windows/Linux) or Shift+Option+F (macOS) using the built-in formatter or Prettier.
  • On the command line, jq . and python -m json.tool format JSON from pipes or files instantly.
  • In code, JSON.stringify(obj, null, 2) (JavaScript) and json.dumps(obj, indent=2) (Python) produce formatted output.
  • Minification reverses the process, stripping whitespace to reduce payload size for production APIs and storage.
  • Always validate JSON before using it in production to catch trailing commas, unquoted keys, and encoding errors.
  • For configuration files, consider YAML or TOML when you need comments or more human-friendly syntax.

What Is JSON and Why Format It?

JSON (JavaScript Object Notation) is the most widely used data interchange format on the web. APIs, configuration files, NoSQL databases, log systems, and message queues all rely on JSON to transmit structured data between services. A typical REST API response might return thousands of characters of tightly packed JSON on a single line. While machines parse this without issue, developers need to read, understand, and debug that data.

JSON formatting (also known as JSON beautifying or JSON pretty-printing) is the process of adding consistent indentation, line breaks, and spacing to raw JSON text. An unformatted payload like {"name":"Alice","roles":["admin","dev"],"settings":{"theme":"dark"}} becomes a clearly structured document where every key, value, nested object, and array element occupies its own line with proper indentation.

Formatting JSON is not about changing the data. The semantic content remains identical. What changes is the visual representation, making it possible to quickly identify nesting levels, spot missing commas, find mismatched brackets, and verify that the structure matches what your application expects. Whether you call it a JSON formatter, JSON beautifier, JSON prettifier, or JSON pretty printer, the underlying operation is the same: parse the JSON string into a data structure, then serialize it back with whitespace and indentation.

JSON Formatter Online — Paste and Beautify

The fastest way to format JSON is to use a browser-based tool. No installation, no configuration, no dependencies. Just paste your JSON and get formatted output instantly. Our JSON formatter online tool provides:

  • Instant formatting: Paste raw JSON on the left, see beautified output on the right in real time.
  • Syntax validation: Errors are highlighted with line numbers so you can fix issues immediately.
  • Customizable indentation: Choose between 2 spaces, 4 spaces, or tab-based indentation.
  • One-click copy: Copy the formatted result to your clipboard with a single button.
  • Minification mode: Switch to compact mode to strip all whitespace for production payloads.
  • No data leaves your browser: All processing happens client-side in JavaScript.

This is ideal when you receive a JSON response from curl, an API testing tool like Postman, or a log aggregation system and need to quickly inspect the structure. Instead of squinting at a wall of text, you get a clean tree of key-value pairs. Try it now: format JSON online.

If you also need to convert between formats, check out our JSON to YAML converter and CSV to JSON converter.

JSON Formatting in VS Code

Visual Studio Code is the most popular editor for web developers, and it includes built-in JSON formatting support. Here are the primary methods to format JSON in VS Code:

Built-in Formatter

VS Code ships with a JSON language service that can format any .json file or JSON content in other file types:

  1. Open a .json file (or paste JSON into a new file and set the language mode to JSON).
  2. Press Shift+Alt+F (Windows/Linux) or Shift+Option+F (macOS).
  3. Alternatively, right-click and select Format Document from the context menu.
  4. The JSON is instantly reformatted with the configured indentation (default: 4 spaces).

To change the default indentation size, open VS Code Settings and search for editor.tabSize. You can also set language-specific formatting preferences:

// settings.json
{
  "[json]": {
    "editor.defaultFormatter": "vscode.json-language-features",
    "editor.tabSize": 2,
    "editor.formatOnSave": true
  }
}

Prettier Extension

For more consistent formatting across your entire project, install the Prettier - Code formatter extension. Prettier enforces a single formatting style for JSON (and many other file types) across all team members:

// .prettierrc
{
  "tabWidth": 2,
  "useTabs": false,
  "printWidth": 80
}

Once installed, set Prettier as the default formatter for JSON files in your VS Code settings:

{
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

With editor.formatOnSave enabled, every time you save a JSON file, Prettier will automatically format it. This is particularly useful for config files like package.json, tsconfig.json, and .eslintrc.json.

JSON Formatting in the Command Line

When you are working in a terminal, SSH session, or CI/CD pipeline, you need command-line tools to format JSON. Two tools dominate this space: jq and Python's built-in json.tool module.

Using jq

jq is a lightweight, portable JSON processor. The simplest formatting command is:

# Format JSON from a file
jq . data.json

# Format JSON from a curl response
curl -s https://api.example.com/users | jq .

# Format with 4-space indentation
jq --indent 4 . data.json

# Format and sort keys alphabetically
jq -S . data.json

# Format with color output (default in terminal)
jq . data.json

# Extract and format a specific field
curl -s https://api.example.com/users | jq '.data[] | {name, email}'

jq is available via brew install jq (macOS), apt install jq (Debian/Ubuntu), or choco install jq (Windows). It goes far beyond formatting: you can filter, transform, and query JSON data with its powerful expression language. Learn more in our jq command tutorial.

Using python -m json.tool

If Python is installed (it comes preinstalled on most systems), you can format JSON without installing anything extra:

# Format JSON from a file
python3 -m json.tool data.json

# Format JSON from stdin (pipe)
echo '{"name":"Alice","age":30}' | python3 -m json.tool

# Format with sorted keys
python3 -m json.tool --sort-keys data.json

# Format with custom indentation (Python 3.9+)
python3 -m json.tool --indent 4 data.json

# Format a curl response
curl -s https://api.example.com/users | python3 -m json.tool

The json.tool module also validates the JSON and returns a non-zero exit code if the input is invalid, making it useful in shell scripts and CI checks.

JSON Formatting in JavaScript

JavaScript provides built-in JSON formatting through JSON.stringify(). The third parameter controls indentation:

// Basic formatting with 2-space indentation
const data = { name: "Alice", age: 30, roles: ["admin", "developer"], settings: { theme: "dark", notifications: true } };

const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// Output:
// {
//   "name": "Alice",
//   "age": 30,
//   "roles": [
//     "admin",
//     "developer"
//   ],
//   "settings": {
//     "theme": "dark",
//     "notifications": true
//   }
// }

// Using tab indentation
const tabFormatted = JSON.stringify(data, null, "\t");

// Using a replacer function to filter fields
const filtered = JSON.stringify(data, ["name", "age"], 2);
// Output:
// {
//   "name": "Alice",
//   "age": 30
// }

// Format a JSON string (parse first, then stringify)
const raw = '{"name":"Alice","age":30}';
const pretty = JSON.stringify(JSON.parse(raw), null, 2);
console.log(pretty);

In Node.js, you can create a simple command-line formatter:

// format-json.mjs
import { readFileSync } from 'fs';

const input = readFileSync(process.argv[2] || '/dev/stdin', 'utf8');
try {
  const parsed = JSON.parse(input);
  console.log(JSON.stringify(parsed, null, 2));
} catch (err) {
  console.error('Invalid JSON:', err.message);
  process.exit(1);
}

Run it with node format-json.mjs data.json or cat data.json | node format-json.mjs. This pattern is used in many build tools and linters that need to read, modify, and write JSON files.

JSON Formatting in Python

Python's json module provides comprehensive JSON formatting capabilities:

import json

data = {
    "name": "Alice",
    "age": 30,
    "roles": ["admin", "developer"],
    "settings": {
        "theme": "dark",
        "notifications": True
    }
}

# Format with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)

# Format with sorted keys
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)
print(formatted_sorted)

# Format with custom separators (compact but readable)
compact = json.dumps(data, separators=(',', ':'))
print(compact)  # No extra whitespace

# Pretty-print with ensure_ascii=False (preserve Unicode)
data_unicode = {"name": "Alice", "city": "Zurich"}
print(json.dumps(data_unicode, indent=2, ensure_ascii=False))

# Read from file, format, and write back
with open('data.json', 'r') as f:
    raw = json.load(f)

with open('data_formatted.json', 'w') as f:
    json.dump(raw, f, indent=2, ensure_ascii=False)
    f.write('\n')  # Trailing newline

# One-liner to format a JSON string
raw_str = '{"name":"Alice","age":30}'
pretty = json.dumps(json.loads(raw_str), indent=2)
print(pretty)

For large JSON files, Python's json module handles them efficiently. For extremely large files (hundreds of MB), consider streaming parsers like ijson or orjson for better performance.

JSON Minification: When and How

Minification is the opposite of formatting: it removes all unnecessary whitespace, newlines, and indentation from JSON to produce the smallest possible payload. While formatted JSON is essential for development and debugging, minified JSON is preferred for:

  • API responses: Reducing bandwidth usage, especially for mobile clients.
  • Local storage: Fitting more data into browser localStorage or sessionStorage (limited to 5-10 MB).
  • Log files: Storing more records per line when using structured logging (one JSON object per line).
  • Message queues: Reducing message size in Kafka, RabbitMQ, or SQS.
  • Database storage: Saving disk space in NoSQL databases like MongoDB or DynamoDB.

Minification Examples

// JavaScript: minify JSON
const data = { name: "Alice", age: 30, roles: ["admin"] };
const minified = JSON.stringify(data);
// Output: {"name":"Alice","age":30,"roles":["admin"]}

// Minify a formatted JSON string
const formatted = `{
  "name": "Alice",
  "age": 30
}`;
const min = JSON.stringify(JSON.parse(formatted));
# Python: minify JSON
import json

data = {"name": "Alice", "age": 30, "roles": ["admin"]}
minified = json.dumps(data, separators=(',', ':'))
# Output: {"name":"Alice","age":30,"roles":["admin"]}
# Command line: minify with jq
jq -c . data.json

# Minify with Python
python3 -c "import json,sys; print(json.dumps(json.load(sys.stdin), separators=(',',':')))" < data.json

You can also use our JSON formatter tool which includes a minification toggle to switch between formatted and minified output.

JSON Validation: Catch Errors Before They Break Production

JSON formatting tools often double as validators. When you paste invalid JSON, the formatter will report an error with details about what went wrong and where. Common JSON validation errors include:

ErrorInvalid JSONFix
Trailing comma{"a": 1, "b": 2,}Remove the trailing comma after the last value
Single quotes{'name': 'Alice'}Replace single quotes with double quotes
Unquoted keys{name: "Alice"}Wrap all keys in double quotes
Comments{"a": 1 // comment}Remove comments (JSON does not support them)
Missing comma{"a": 1 "b": 2}Add a comma between key-value pairs
Undefined / NaN{"value": undefined}Use null instead of undefined or NaN

For a deep dive into parsing errors, see our guide on JSON parse error: unexpected token. For schema-level validation (ensuring the data structure matches what your application expects), check out our JSON Schema validation guide.

You can validate JSON programmatically in JavaScript with a simple try-catch block:

function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

console.log(isValidJSON('{"name": "Alice"}')); // true
console.log(isValidJSON('{name: "Alice"}'));     // false
console.log(isValidJSON(''));                     // false

JSON Viewer: Exploring Nested Data

For deeply nested JSON with hundreds or thousands of fields, a flat text view (even when formatted) can be overwhelming. A JSON viewer provides an interactive, tree-based interface where you can expand and collapse nodes, search for specific keys or values, and navigate complex structures efficiently.

Key features of a good JSON viewer:

  • Collapsible tree view: Expand only the sections you need. Hide everything else to reduce visual noise.
  • Search and filter: Find a specific key or value across the entire JSON document instantly.
  • Type indicators: Visually distinguish strings, numbers, booleans, arrays, and objects with color coding.
  • Path display: See the full JSONPath (e.g., $.data.users[0].name) for any selected node.
  • Copy path/value: Copy the path or value of any node to use in code or API queries.
  • Array length display: See how many items are in each array without expanding it.

Our JSON formatter includes a viewer mode that renders the document as an expandable tree. This is especially useful when exploring API responses from services like Elasticsearch, MongoDB, or GraphQL endpoints that return deeply nested data.

For browser-based debugging, the Chrome DevTools Network tab and Firefox Developer Tools both include built-in JSON viewers that automatically format API responses. You can also install browser extensions like JSONView to automatically format any JSON response displayed in the browser.

Common JSON Syntax Errors and How to Fix Them

Even experienced developers encounter JSON syntax errors regularly. Here are the most common mistakes and how to fix them:

1. Trailing Commas

Unlike JavaScript objects, JSON does not allow trailing commas after the last element in an object or array:

// INVALID - trailing comma
{
  "name": "Alice",
  "age": 30,
}

// VALID
{
  "name": "Alice",
  "age": 30
}

2. Single Quotes Instead of Double Quotes

JSON requires double quotes for all strings and keys. Single quotes are not valid:

// INVALID - single quotes
{'name': 'Alice'}

// VALID - double quotes only
{"name": "Alice"}

3. Unescaped Special Characters in Strings

Backslashes, double quotes, and control characters inside strings must be escaped:

// INVALID - unescaped characters
{"path": "C:\Users\Alice"}
{"message": "She said "hello""}

// VALID - escaped
{"path": "C:\\Users\\Alice"}
{"message": "She said \"hello\""}

4. Comments in JSON

JSON does not support comments. If you need comments in configuration files, consider using JSONC (JSON with Comments, supported by VS Code), JSON5, or switch to YAML or TOML:

// INVALID - comments not allowed
{
  "port": 3000, // server port
  "debug": true  /* enable debug mode */
}

// VALID - no comments
{
  "port": 3000,
  "debug": true
}

5. Numbers with Leading Zeros

// INVALID - leading zeros
{"port": 08080}

// VALID
{"port": 8080}

6. Using undefined, NaN, or Infinity

// INVALID - not valid JSON values
{"value": undefined, "ratio": NaN, "max": Infinity}

// VALID - use null for missing values
{"value": null, "ratio": 0, "max": 999999}

For a comprehensive list of JSON parsing errors and solutions, see our detailed guide: JSON.parse() Unexpected Token Error: Complete Fix Guide.

JSON vs YAML vs TOML: When to Use What

JSON is not the only structured data format. YAML and TOML are popular alternatives, each with distinct strengths. Understanding when to use each format helps you choose the right tool for the job:

FeatureJSONYAMLTOML
CommentsNot supportedSupported (#)Supported (#)
Human readabilityGood (when formatted)ExcellentExcellent
Machine parsing speedFastSlowerFast
Nested dataExcellentGood (indentation-sensitive)Moderate (tables syntax)
Best forAPIs, data exchangeConfig files (Docker, K8s)App config (Cargo, pyproject)
Native date/timeNo (strings only)YesYes
Multiline stringsNo (use \n)Yes (block scalars)Yes (triple quotes)

Use JSON when: Building REST APIs, transmitting data between microservices, storing structured data in databases, or working with JavaScript/TypeScript applications.

Use YAML when: Writing configuration files for Docker Compose, Kubernetes, GitHub Actions, or other DevOps tools that expect YAML.

Use TOML when: Configuring Rust (Cargo.toml), Python (pyproject.toml), or other tools where a flat, INI-like structure with comments is preferred.

For a detailed comparison, read our full guide: JSON vs YAML vs TOML: When to Use What. You can also convert between these formats using our JSON to YAML converter.

Advanced JSON Formatting Tips

Beyond basic pretty-printing, there are several advanced techniques that can make your JSON workflow more efficient:

Sort Keys Alphabetically

Sorting keys makes JSON diffs cleaner in version control. When two developers modify the same config file, unsorted keys can create unnecessary merge conflicts.

# Sort keys with jq
jq -S . config.json > config_sorted.json

# Sort keys in Python
python3 -c "import json,sys; d=json.load(sys.stdin); print(json.dumps(d, indent=2, sort_keys=True))" < config.json
// Sort keys in JavaScript
function sortKeys(obj) {
  if (Array.isArray(obj)) return obj.map(sortKeys);
  if (obj !== null && typeof obj === 'object') {
    return Object.keys(obj).sort().reduce((acc, key) => {
      acc[key] = sortKeys(obj[key]);
      return acc;
    }, {});
  }
  return obj;
}

const sorted = JSON.stringify(sortKeys(data), null, 2);

Format JSON in Git Hooks

Automate JSON formatting by adding a pre-commit hook that formats all JSON files before they are committed:

#!/bin/sh
# .git/hooks/pre-commit
for file in $(git diff --cached --name-only --diff-filter=ACM | grep '\.json$'); do
  jq -S . "$file" > "$file.tmp" && mv "$file.tmp" "$file"
  git add "$file"
done

Handle Large JSON Files

For JSON files exceeding 100 MB, standard tools may run out of memory. Use streaming approaches:

# Stream large JSON with jq (memory efficient for arrays)
jq -c '.[]' large-file.json | head -10

# Use Python's ijson for streaming
pip install ijson
python3 -c "
import ijson, sys
for item in ijson.items(open('large-file.json','rb'), 'item'):
    print(item)
"

JSON Formatting in Different Programming Languages

Beyond JavaScript and Python, here is how to format JSON in other popular languages:

Go

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    raw := []byte(`{"name":"Alice","age":30}`)
    var data interface{}
    json.Unmarshal(raw, &data)
    formatted, _ := json.MarshalIndent(data, "", "  ")
    fmt.Println(string(formatted))
    // Or write to stdout
    enc := json.NewEncoder(os.Stdout)
    enc.SetIndent("", "  ")
    enc.Encode(data)
}

Java

// Using Jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Object json = mapper.readValue(rawJsonString, Object.class);
String formatted = mapper.writeValueAsString(json);

// Using Gson
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement el = JsonParser.parseString(rawJsonString);
String formatted = gson.toJson(el);

PHP

<?php
$raw = '{"name":"Alice","age":30}';
$data = json_decode($raw);
$formatted = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo $formatted;

Ruby

require 'json'
raw = '{"name":"Alice","age":30}'
parsed = JSON.parse(raw)
puts JSON.pretty_generate(parsed)

Rust

use serde_json::Value;

fn main() {
    let raw = r#"{"name":"Alice","age":30}"#;
    let v: Value = serde_json::from_str(raw).unwrap();
    let formatted = serde_json::to_string_pretty(&v).unwrap();
    println!("{}", formatted);
}

If you need to convert JSON into strongly typed code for these languages, check out our dedicated converter tools: JSON to Go, JSON to Java, JSON to Kotlin, and JSON to TypeScript.

JSON Formatter vs JSON Validator vs JSON Viewer: What Is the Difference?

These three terms are often used interchangeably, but they serve different purposes:

ToolPurposeOutput
JSON FormatterAdd indentation and line breaks for readabilityPretty-printed text
JSON ValidatorCheck if JSON is syntactically correct per RFC 8259Valid/invalid + error details
JSON ViewerInteractively explore JSON with collapsible tree navigationTree UI with expand/collapse

Most modern JSON tools combine all three functions. Our JSON formatter formats, validates, and provides a viewer in a single interface. Use it whenever you need to quickly inspect or debug JSON data.

Frequently Asked Questions

What is a JSON formatter?

A JSON formatter (also called a JSON beautifier or JSON prettifier) is a tool that takes raw, minified, or poorly indented JSON and transforms it into a clean, human-readable format with consistent indentation and line breaks. It does not change the data itself, only the visual presentation.

How do I format JSON in VS Code?

Open a JSON file in VS Code and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (macOS) to format the entire document. You can also right-click and select "Format Document." For automatic formatting, enable editor.formatOnSave in your settings. Install the Prettier extension for more consistent cross-project formatting.

How do I format JSON in the terminal?

Use jq . file.json to format a JSON file with jq (install via brew install jq or apt install jq). Alternatively, use python3 -m json.tool file.json which is available on any system with Python installed. Both commands also accept piped input, so you can use curl -s url | jq ..

What is the difference between JSON formatting and JSON validation?

JSON formatting changes the visual layout (adding indentation and line breaks) without modifying data. JSON validation checks whether the JSON is syntactically correct according to the JSON specification (RFC 8259). Most JSON formatters also validate the input and will report errors if the JSON is malformed. Schema validation goes further by checking whether the data structure matches a predefined schema.

Is there a keyboard shortcut to format JSON?

In VS Code: Shift+Alt+F (Windows/Linux) or Shift+Option+F (macOS). In IntelliJ IDEA / WebStorm: Ctrl+Alt+L (Windows/Linux) or Cmd+Option+L (macOS). In Sublime Text: install the Pretty JSON package and use Ctrl+Alt+J. In Vim: use :%!jq . to format the entire buffer.

Can I format JSON with JavaScript?

Yes. Use JSON.stringify(data, null, 2) to format a JavaScript object with 2-space indentation. To format a JSON string, first parse it: JSON.stringify(JSON.parse(jsonString), null, 2). The third parameter can be a number (spaces) or a string (e.g., "\t" for tabs).

How do I minify JSON?

In JavaScript, use JSON.stringify(data) without the third parameter. In Python, use json.dumps(data, separators=(',', ':')). On the command line, use jq -c . file.json. Minification removes all whitespace and line breaks to produce the smallest possible JSON payload.

Does JSON support comments?

No. Standard JSON (RFC 8259) does not support comments. If you need comments, use JSONC (JSON with Comments, supported by VS Code for settings files), JSON5, YAML, or TOML instead. Some tools strip comments as a preprocessing step before parsing.

Why is my JSON not formatting correctly?

The most common reasons are: (1) the JSON is invalid (trailing commas, single quotes, unquoted keys, comments), (2) the file has a BOM (byte order mark) at the beginning, (3) the encoding is not UTF-8, or (4) the JSON is actually a JavaScript object literal (not valid JSON). Try pasting your JSON into a validator to see the exact error.

What is the best free JSON formatter online?

A good online JSON formatter should be fast, handle large files, validate syntax, support customizable indentation, and process everything client-side for privacy. Our DevToolBox JSON formatter meets all these criteria and is completely free with no sign-up required.

Related Tools and Resources

Explore more JSON tools and guides on DevToolBox:

𝕏 Twitterin LinkedIn
War das hilfreich?

Bleiben Sie informiert

Wöchentliche Dev-Tipps und neue Tools.

Kein Spam. Jederzeit abbestellbar.

Verwandte Tools ausprobieren

{ }JSON Formatter✓JSON ValidatorY{}JSON ↔ YAML Converter📊CSV ↔ JSON ConverterTSJSON to TypeScriptGoJSON to Go Struct

Verwandte Artikel

JSON vs YAML vs TOML: Welches Config-Format sollten Sie verwenden?

Vergleichen Sie JSON, YAML und TOML Konfigurationsformate.

JSON Parse Error: Unexpected Token — Finden und Beheben

JSON-Parse-Fehler Schritt fĂŒr Schritt beheben. Ursachen, Problemlokalisierung und Validierungstools.

JSON Formatter & Validator: JSON Online Formatieren und Validieren

Kostenloser Online JSON Formatter und Validator. JSON formatieren, Syntaxfehler finden, mit Code-Beispielen in JavaScript und Python.