How to Pretty Print JSON (All Methods)

22 Feb 2026 1,427 words

How to Pretty Print JSON

Pretty printing JSON makes raw data readable with proper indentation and line breaks. This is essential for debugging, documentation, API development, and any scenario where humans need to inspect structured data. Without pretty printing, JSON appears as a single, unbroken line of text that is nearly impossible to parse visually. This guide covers every method to format JSON across different environments, from online tools to command-line utilities and code libraries.

What Is Pretty Printing?

Pretty printing (also called beautifying or formatting) takes compact JSON and adds whitespace to make it human-readable. A compact JSON object like {"name":"John","age":30,"hobbies":["reading","coding"]} becomes a structured, indented representation:

{
  "name": "John",
  "age": 30,
  "hobbies": [
    "reading",
    "coding"
  ]
}

The process does not change the data — only its visual presentation. Most pretty printers offer configurable indentation (2 spaces, 4 spaces, or tabs) and optional sorting of keys. Some also offer syntax highlighting, collapsible tree views, and error highlighting for invalid JSON.

Online Method

The Help2Code JSON Formatter tool provides instant formatting with syntax highlighting, validation, and a tree view. It is the fastest way to format JSON without installing any software. Simply paste your JSON string into the input area, and the tool formats it in real time. Key features include:

  • Real-time formatting as you type or paste
  • Syntax highlighting for keys, strings, numbers, booleans, and null values
  • JSON validation with line-specific error messages
  • Collapsible tree view for navigating deeply nested structures
  • Download formatted output as a file
  • Minify mode to compress formatted JSON back to compact form
  • Copy to clipboard with one click

This tool is ideal for developers who need to quickly inspect API responses, debug configuration files, or share formatted JSON with colleagues.

Method Comparison

Method Speed Offline Best For
Help2Code JSON Formatter Instant No Quick formatting, one-off tasks
Browser DevTools Fast Yes Debugging API responses during development
VS Code Fast Yes Development workflow, file editing
jq (CLI) Fastest Yes Scripts, automation, pipe processing
JavaScript Depends Yes Programmatic formatting in web apps
Python Fast Yes Data processing pipelines
PHP Fast Yes Server-side formatting before output
Ruby Fast Yes Rails and Ruby applications
IntelliJ IDEA Fast Yes Enterprise Java/Kotlin development

Browser DevTools

All modern browsers include built-in JSON pretty printing in their developer tools. When you log objects to the console using console.log(), the browser automatically displays them in a collapsible, interactive tree view. However, for more control over formatting, use JSON.stringify() with formatting options:

// In browser console
const data = {
  name: "John",
  age: 30,
  hobbies: ["reading", "coding"],
  address: {
    street: "123 Main St",
    city: "Boston",
    zip: "02101"
  }
};

// Pretty print with 2-space indentation
console.log(JSON.stringify(data, null, 2));

// Pretty print with 4-space indentation
console.log(JSON.stringify(data, null, 4));

// Pretty print with tab indentation
console.log(JSON.stringify(data, null, '\t'));

// Using console.table for arrays of objects
const users = [
  { id: 1, name: "Alice", role: "Admin" },
  { id: 2, name: "Bob", role: "User" }
];
console.table(users);

The Chrome DevTools Network tab also includes a built-in JSON viewer for API responses. When a response has Content-Type: application/json, the Preview tab automatically formats and syntax-highlights the response body with collapsible sections.

VS Code

Visual Studio Code provides excellent JSON editing and formatting support out of the box:

  1. Format Document: Select JSON content and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac), or right-click and select "Format Document".
  2. Auto-format on save: Add "editor.formatOnSave": true to your settings.json to automatically format JSON files when saving.
  3. JSON with Comments (.jsonc): VS Code supports JSON files that contain comments, commonly used for configuration files like settings.json and launch.json.

Additional VS Code extensions for JSON handling include:

  • Prettier - Code formatter that supports JSON with customizable options
  • JSON Tools - Adds sort, minify, and format commands
  • Bracket Pair Colorizer - Color-codes matching brackets for deeply nested JSON

Command Line (jq)

jq is a powerful command-line JSON processor that handles formatting, filtering, transformation, and querying. It is available on all platforms via package managers and is the go-to tool for JSON manipulation in scripts:

# Basic formatting - pipe JSON to jq with the identity filter
echo '{"name":"test","value":123}' | jq .

# Colorized output (disabled by default in pipes)
echo '{"name":"test"}' | jq -C .

# Read from file and format
jq . file.json

# Save formatted output
jq . file.json > formatted.json

# Format with specific indentation (default is 2)
jq --indent 4 . file.json

# Minify JSON (remove all whitespace)
jq -c . file.json

# Sort object keys alphabetically
jq -S . file.json

# Extract and format a specific field
cat data.json | jq '.users' | jq .

# Pretty print and colorize in one command
cat messy.json | jq -C . | less -R

jq can also be combined with other command-line tools for powerful data processing pipelines:

# Fetch API response and format it
curl https://api.example.com/users | jq .

# Format only the first N items
curl https://api.example.com/users | jq '.[:5]'

# Transform and format
cat data.json | jq '{name: .user.name, email: .user.email}'

Language-Specific Methods

Every major programming language includes built-in or library-based JSON pretty printing:

JavaScript:

const pretty = JSON.stringify(obj, null, 2); // 2-space indent
const compact = JSON.stringify(obj); // no whitespace

// With custom replacer function to filter/transform values
const filtered = JSON.stringify(obj, ['name', 'age'], 2);

// Custom replacer to redact sensitive fields
const redacted = JSON.stringify(obj, (key, value) => {
  if (key === 'password' || key === 'ssn') return '***';
  return value;
}, 2);

// Using util.inspect in Node.js for more control
const util = require('util');
console.log(util.inspect(obj, { colors: true, depth: null, sorted: true }));

Python:

import json

data = {"name": "John", "age": 30, "active": True}

# Basic pretty print with 2-space indent
pretty = json.dumps(data, indent=2)

# Sort keys alphabetically
pretty = json.dumps(data, indent=2, sort_keys=True)

# Ensure non-ASCII characters are preserved (not escaped)
pretty = json.dumps(data, indent=2, ensure_ascii=False)

# Custom separators for more compact output
compact = json.dumps(data, separators=(',', ':'))

# Pretty print directly to console
print(json.dumps(data, indent=2, sort_keys=True))

PHP:

$data = ["name" => "John", "age" => 30, "hobbies" => ["reading"]];

// Basic pretty print
$pretty = json_encode($data, JSON_PRETTY_PRINT);

// Preserve Unicode characters
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Sort keys
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_SORT_KEYS);

// Format with escaping for HTML
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP);

Ruby:

require 'json'

data = { name: "John", age: 30, active: true }

# Pretty print
puts JSON.pretty_generate(data)

# Custom options
puts JSON.pretty_generate(data, indent: "    ")

Go:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    data := map[string]interface{}{
        "name": "John",
        "age": 30,
    }
    pretty, _ := json.MarshalIndent(data, "", "  ")
    fmt.Println(string(pretty))
}

JSON Validation While Formatting

Most pretty printing tools also validate JSON syntax. Invalid JSON cannot be formatted because the parser cannot determine the intended structure. Common JSON validation errors include:

  • Trailing commas ([1, 2,]) - Although allowed in JavaScript, trailing commas are invalid in JSON
  • Single quotes ('value') - JSON requires double quotes for strings
  • Missing quotes around keys ({name: "John"}) - Keys must be quoted
  • Unescaped control characters - Tab, newline, and carriage return must be escaped as \t, \n, \r
  • Comments - JSON does not support comments; use JSONC format if comments are needed

When to Use Which Method

Choosing the right method depends on your workflow:

  • One-off formatting: Online tool (fastest, no installation)
  • During development: Browser DevTools or VS Code (integrated into your workflow)
  • In scripts and automation: jq (pipeline-friendly, scriptable)
  • Programmatic formatting in applications: Language-specific methods (JavaScript JSON.stringify, Python json.dumps, PHP json_encode)
  • Large files: jq or command-line tools (memory efficient for streaming)

Conclusion

Pretty printing JSON is a fundamental skill for any developer working with APIs, configuration files, or data processing. With methods available for every environment — from online tools to command-line utilities to every major programming language — there is always a way to make your JSON readable. The key is choosing the right tool for your context: fast and convenient for quick inspections, powerful and scriptable for automated pipelines.


About this article

Learn all methods to pretty print JSON data in browsers, editors, command line, and programming languages.

Help2Code Logo
Menu