JSON Pretty Print Online
Free online JSON beautifier — paste compact or minified JSON and get instant, readable output. Supports 2-space, 4-space, and tab indentation. 100% browser-based, no signup.
Definition
What is JSON Pretty Print?
JSON pretty print — also called JSON beautify — transforms compact or minified JSON into human-readable format by adding indentation and line breaks. The data never changes: keys, values, types, and structure are identical before and after. Only whitespace is added.
What changes
Whitespace only
What stays
All data & types
Input
Compact JSON
Output
Indented JSON
What Is JSON Pretty Print?
JSON pretty print — also known as JSON beautify — transforms compact or minified JSON into a hierarchically indented, human-readable layout. Each level of nesting is indented one step further, making it immediately clear which values belong to which objects and arrays. The output is byte-for-byte equivalent in meaning to the input; only whitespace changes.
This tool is optimized for one thing: instant readability. Unlike a full JSON Formatter with configurable rules, pretty print applies sensible defaults with zero configuration. Paste minified JSON, press Ctrl+Enter — done. For complex structural exploration, use the JSON Viewer which renders JSON as a collapsible tree.
Features at a Glance
- check_circleInstant beautification — paste and it's done
- check_circleAuto-beautifies valid JSON when you paste
- check_circleCtrl+Enter keyboard shortcut
- check_circle2-space, 4-space, or tab indentation
- check_circleDownload beautified output as .json file
- check_circleCopy output to clipboard with feedback
- check_circleLoad sample to see the result instantly
- check_circlePrivate by design — 100% browser-based
JSON Beautification: Before & After
This is what pretty printing JSON does to a real API response. The data is identical — only the whitespace changes. Notice how the nested objects and array structure become immediately navigable in the beautified version:
Before — Minified (1 line, 237 characters)
Impossible to read at a glance{"user":{"id":1042,"name":"Alice Chen","email":"alice@example.com","role":"admin","active":true,"preferences":{"theme":"dark","notifications":true,"language":"en"}},"permissions":["read","write","delete"],"metadata":{"version":"2.1","source":"api","count":3}}After — Beautified (30 lines, instantly readable)
Structure visible at a glance{
"user": {
"id": 1042,
"name": "Alice Chen",
"email": "alice@example.com",
"role": "admin",
"active": true,
"preferences": {
"theme": "dark",
"notifications": true,
"language": "en"
}
},
"permissions": [
"read",
"write",
"delete"
],
"metadata": {
"version": "2.1",
"source": "api",
"count": 3
}
}Same data, different readability. The minified version and the beautified version parse to the exact same JavaScript object. Pretty printing adds zero semantic content — it only adds whitespace that humans can use to navigate the structure. Click above to run this example in the tool.
How to Beautify JSON Online — 3 Steps
Three steps, under 10 seconds. Valid JSON auto-beautifies on paste — no button press needed.
Paste compact or minified JSON
Copy the compact JSON you want to beautify — from an API response, a log file, a database field, or a curl output — and paste it into the input panel. If the JSON is valid, it beautifies automatically on paste.
Choose indentation style
Select your preferred indentation: 2 spaces (default, most common), 4 spaces (Python/Java style), or tab (editor-controlled width). Press Ctrl+Enter or click Pretty Print to apply. Switch styles at any time — the output updates instantly.
Copy or download the beautified output
The beautified JSON appears in the output panel. Click Copy to copy to your clipboard, or Download to save it as a .json file. Paste it into your editor, docs, API client, or code review.
2-Space vs 4-Space vs Tab: Which JSON Indentation Should You Use?
Indentation style doesn't change the data — but it matters for readability, file size, and consistency with your team or project's existing conventions. Here's a practical guide to each option:
2 Spaces Indentation
Most PopularAdvantages
- ✓Used by npm, Node.js, and the majority of public APIs
- ✓Compact — deeply nested JSON stays within viewport width
- ✓Google, Airbnb, and most popular style guides recommend it
- ✓Smaller file size than 4-space for the same structure
Trade-offs
- ·Less visual separation — harder to distinguish levels at 5+ nesting depth
Best For
Web APIs, Node.js projects, sharing JSON in Slack or docs, any situation where file size or line length matters.
Example
{
"name": "Alice",
"address": {
"city": "London"
}
}4 Spaces Indentation
Python / Java StandardAdvantages
- ✓More visual breathing room between nesting levels
- ✓Standard in Python (PEP 8), Java, and C# projects
- ✓Easier to distinguish levels in deeply nested structures
Trade-offs
- ·Lines get long faster — deeply nested JSON may exceed 80 or 120 character limits
- ·Roughly twice the file size increase vs 2-space for the same structure
Best For
Python/Django projects, Java or .NET backends, JSON configuration files where visual clarity is more important than line length.
Example
{
"name": "Alice",
"address": {
"city": "London"
}
}Tab Indentation
Editor-ControlledAdvantages
- ✓Each viewer's editor controls the visual tab width (usually 2 or 4)
- ✓Smallest character-count overhead (one character per level vs 2 or 4 spaces)
- ✓Preferred by projects using editorconfig with tab indent settings
Trade-offs
- ·Renders differently across tools — same JSON looks different in VS Code vs a terminal
- ·Not recommended for JSON shared across teams with different editor settings
Best For
Projects with a strict editorconfig that enforces tabs, or when the JSON is consumed only by your own tooling.
Example
{
"name": "Alice",
"address": {
"city": "London"
}
}Bottom line: Use 2-space by default — it's the most widely compatible choice for JSON. Switch to 4-space if your team's existing JSON files use it. Use tab only if your project enforces it via editorconfig or a linter.
Why JSON Readability Matters
Minified JSON is optimal for machines — compact, fast to transmit, efficient to parse. But when humans need to read it — during debugging, code review, documentation, or incident response — minified JSON becomes a liability. Here's the concrete impact of JSON readability on real workflows:
Code Reviews
When a pull request includes a JSON fixture, config change, or test payload, reviewers need to understand the structure. Minified JSON in a PR diff is unreadable — reviewers skip it. Pretty-printed JSON reveals what changed at a glance, catching bugs before they merge.
Debugging & Incident Response
Finding the wrong field value in a 500-character minified JSON string during an incident takes 10× longer than scanning a properly indented structure. Every second of readability friction compounds during time-critical debugging.
API Documentation
API docs that show minified example responses signal low quality to developers evaluating the API. Well-indented, readable JSON in docs improves developer experience, reduces support questions, and increases API adoption.
Team Collaboration
When sharing JSON data in Slack messages, GitHub issues, or Notion pages, pretty-printed JSON communicates structure without requiring the reader to parse it mentally. Minified JSON forces unnecessary cognitive work on every reader.
Understanding Data Structure
When working with an unfamiliar API response, pretty printing reveals the object hierarchy, array lengths, nested field names, and data types in seconds. Without it, you'd need to map the structure manually or use a dedicated JSON tree tool.
JSON Config File History
In version-controlled JSON config files (package.json, tsconfig.json, CI configs), consistent indentation makes git diffs clean and meaningful. A single pretty-print standardization prevents whitespace noise in file history.
When to Use a JSON Beautifier
A JSON beautifier is the right tool whenever you have compact JSON you need to read quickly — without modifying the data or doing complex analysis. Here are the most common scenarios:
Reading API Responses
API responses arrive as a single minified line. Paste into the beautifier to reveal the full object hierarchy, array lengths, and field names in seconds — much faster than counting brackets manually.
Inspecting Server Logs
Structured JSON logs from servers, Lambda functions, or monitoring systems are compacted for storage efficiency. Beautify a log entry to make it instantly readable during debugging or an incident.
API Documentation
Paste readable, indented JSON into API docs, README files, or code review comments. Minified JSON is unreadable in a PR diff; beautified JSON communicates structure clearly to every reader.
Database JSON Columns
JSON stored in database TEXT or JSONB columns is often compact for storage efficiency. Beautify before pasting into migration scripts, queries, or documentation.
Sharing in Slack or Issues
When posting JSON in Slack, GitHub issues, or Jira tickets, pretty-printed JSON communicates structure at a glance. Minified JSON forces every reader to do unnecessary mental parsing.
Comparing Two JSON Structures
Before diffing two JSON responses, beautify both. A character-level diff of minified JSON produces noise. Beautified JSON diffs show exactly which key-value pairs changed, added, or removed.
How JSON Pretty Print Reveals Nested Structure
Flat JSON is easy to scan minified — a few keys and values on one line are readable. But real-world API responses, configuration schemas, and event payloads are deeply nested: objects inside objects inside arrays inside objects. At five or more levels of nesting, minified JSON becomes completely opaque. Pretty printing adds visual hierarchy that replaces the need to count brackets manually.
The indentation level tells you exactly which object owns each field — instantly, without parsing. It's the only reliable navigation tool for nested JSON short of a full tree viewer.
Before — 7 Levels Deep (Minified, 1 line)
Which object owns "email"? Impossible to tell.{"api":{"version":"v2","endpoints":{"users":{"list":{"auth":true,"params":{"pagination":{"page":1,"limit":50},"filters":{"role":"admin","active":true}},"response":{"data":[{"id":1,"profile":{"name":"Alice","contact":{"email":"alice@example.com"}}}],"meta":{"total":142}}}}}}}After — 7 Nesting Levels, Instantly Navigable
Hierarchy visible without counting a single bracket{
"api": {
"version": "v2",
"endpoints": {
"users": {
"list": {
"auth": true,
"params": {
"pagination": {
"page": 1,
"limit": 50
},
"filters": {
"role": "admin",
"active": true
}
},
"response": {
"data": [
{
"id": 1,
"profile": {
"name": "Alice",
"contact": {
"email": "alice@example.com"
}
}
}
],
"meta": {
"total": 142
}
}
}
}
}
}
}| Indent Level | Field(s) | What You Learn Instantly |
|---|---|---|
| Level 0 (root) | api | Top-level namespace — this is an API configuration object |
| Level 1 | version, endpoints | Two top-level keys — version info and endpoint definitions grouped separately |
| Level 2 | users | A resource grouping under endpoints — other resources appear as siblings |
| Level 3 | list | An operation on the users resource — "create", "delete" etc. would be siblings here |
| Level 4 | auth, params, response | Three aspects of the list operation — security, input parameters, and output shape all visible at once |
| Level 5 | pagination, filters · data, meta | Sub-structures of params and response — each group visually separated |
| Level 6 | page, limit · role, active · id, profile | Leaf fields — instantly clear which group each one belongs to |
The indentation IS the documentation. In deeply nested JSON, each indent level tells you the full ownership chain. You can answer "which object does email belong to?" in one glance — without counting a single bracket. For interactive collapse/expand navigation of very deep structures, use the JSON Viewer.
Format JSON for Readable Output
Valid JSON parses without errors. Readable JSON communicates structure to a human in seconds. Pretty printing bridges the gap — but readable output is a broader goal than indentation alone. Here's a complete picture of what makes formatted JSON genuinely readable, and when it matters most.
Consistent Indentation
Every nesting level indented one step further. 2 spaces is the most readable for most JSON — compact enough to stay within viewport width, clear enough to distinguish levels.
One Value Per Line
Each key-value pair on its own line. Arrays with multiple elements have one element per line. No "compressed" sub-objects squeezed onto one line.
Reasonable Line Length
At 2-space indentation, deeply nested JSON stays within 80–120 character line limits. At 4-space, deeply nested structures exceed line limits quickly.
When Readable JSON Output Matters Most
API Documentation
Example requests and responses in API docs must be readable at a glance. Minified JSON in docs signals low quality and increases developer integration time. Pretty-printed examples communicate the full response shape — field names, nesting, arrays, data types — without any explanation needed.
Code Review & Pull Requests
JSON fixtures, test payloads, and config changes in PRs need to be reviewable. Beautified JSON in a diff shows exactly what changed — a field was added, a value changed, a nested object was restructured. Minified JSON diffs are character-level noise that reviewers skip.
Incident Response & Debugging
When a production incident requires reading JSON log entries or error payloads under time pressure, readability directly affects mean time to resolution. Format log samples before pasting into incident channels, postmortems, or Slack threads.
| Goal | Best Choice | Why |
|---|---|---|
| Reading an API response | 2-space pretty print | Compact, universally readable, fits most displays and doc widths |
| Config file in git repo | 2-space or 4-space | Match your project's existing style for clean git diffs |
| Paste in Slack or GitHub issue | 2-space pretty print | Stays within width limits; 4-space may force horizontal scrolling |
| API documentation example | 2-space pretty print | Most README renderers and doc tools prefer 2-space indented JSON |
| Sharing with non-technical reader | 4-space pretty print | Extra visual spacing makes nested structure clearer for non-developers |
| Production API payload | Minify | Strip all whitespace — readable JSON is for humans, minified JSON is for machines |
Pretty Print JSON in Your Tools
Every developer tool in common use has a built-in way to pretty print JSON — often automatically. Here's how to use each one:
VS Code
- 1.Open any .json file in VS Code
- 2.Press Alt+Shift+F (Windows/Linux) or Shift+Option+F (Mac)
- 3.Or right-click → "Format Document" → select JSON formatter
- 4.VS Code's built-in JSON language server handles the formatting with your configured tab size
Tip: Set "editor.formatOnSave": true in settings.json to auto-beautify every time you save a .json file.
Chrome DevTools
- 1.Open DevTools (F12) → Network tab
- 2.Click any request that returns JSON
- 3.Click the "Response" or "Preview" tab
- 4.Chrome auto-renders JSON as a collapsible tree in Preview, or pretty-prints in Response
Tip: The Preview tab in Chrome DevTools is essentially a built-in JSON viewer. Use Response for the raw pretty-printed text.
curl + jq
- 1.Install jq: brew install jq (macOS) or apt install jq (Linux)
- 2.Pipe any curl output to jq: curl https://api.example.com/data | jq .
- 3.The . filter is a no-op that triggers jq's default pretty printing
- 4.Add -r flag for raw string output: curl ... | jq -r '.[].name'
Tip: jq . is the fastest way to pretty print JSON from any command-line source. Add --color-output (-C) to preserve colors when piping further.
Python (built-in)
- 1.Run: python3 -m json.tool compact.json
- 2.Or pipe: echo '{"a":1}' | python3 -m json.tool
- 3.Output goes to stdout — redirect to a file: python3 -m json.tool in.json > out.json
- 4.Add --indent 4 for 4-space indentation: python3 -m json.tool --indent 4 in.json
Tip: Python's json.tool is available on every system with Python 3 — no package install needed. It's the go-to for quick CLI beautification when jq isn't installed.
Postman
- 1.After sending a request, click the "Pretty" tab in the response section
- 2.Postman auto-detects JSON and renders it in a collapsible, syntax-highlighted view
- 3.Use "Raw" for the minified version or "Preview" for a rendered view
- 4.Click the copy icon to copy the pretty-printed JSON to clipboard
Tip: Postman's Pretty view uses 2-space indentation by default. The online editor above lets you switch to 4-space or tab if your project style requires it.
Insomnia
- 1.After sending a request, click the "Pretty" tab in the response panel
- 2.Insomnia auto-detects JSON content and renders a syntax-highlighted, indented view
- 3.Use "Raw" to see the minified original, or "Preview" for a browser-rendered HTML view
- 4.Click the copy icon in the top-right to copy the prettified response to clipboard
Tip: Insomnia's Pretty view uses 2-space indentation. If you need a different indent style or want to download the output as a file, paste the response into the tool above and choose your indentation.
Pretty Print JSON in Code
Every major language has a built-in way to pretty print JSON. Use these for development logging, debugging output, or generating human-readable JSON files:
JavaScript / Node.js
// 2-space indent (most common)
JSON.stringify(data, null, 2);
// 4-space indent
JSON.stringify(data, null, 4);
// Tab indent
JSON.stringify(data, null, '\t');
// Write pretty-printed file (Node.js)
const fs = require('fs');
fs.writeFileSync('out.json',
JSON.stringify(data, null, 2));Python
import json
# Print to console
print(json.dumps(data, indent=2))
# Write to file
with open('out.json', 'w') as f:
json.dump(data, f, indent=2)
# CLI: python3 -m json.tool in.json
# CLI: cat in.json | python3 -m json.toolGo
import (
"encoding/json"
"fmt"
)
// MarshalIndent: prefix="", indent=" "
b, err := json.MarshalIndent(data, "", " ")
if err != nil { panic(err) }
fmt.Println(string(b))Command Line (jq)
# Pretty print a file
jq . compact.json
# Pretty print from stdin
cat compact.json | jq .
echo '{"a":1}' | jq .
# Pretty print and write to file
jq . compact.json > pretty.json
# Python alternative (no install needed)
python3 -m json.tool in.jsonRuby
require 'json'
# Parse and pretty print to console
data = JSON.parse(compact_json)
puts JSON.pretty_generate(data)
# JSON.pretty_generate uses 2-space indent by default
# Write to file
File.write('out.json', JSON.pretty_generate(data))
# One-liner CLI
# echo '{"a":1}' | ruby -rjson -e # 'puts JSON.pretty_generate(JSON.parse(STDIN.read))'PHP
<?php
// Parse and pretty print
$data = json_decode($compactJson);
echo json_encode($data, JSON_PRETTY_PRINT);
// JSON_PRETTY_PRINT uses 4-space indentation
// Write to file
file_put_contents('out.json',
json_encode($data, JSON_PRETTY_PRINT));
// With Unicode + slashes unescaped
echo json_encode($data,
JSON_PRETTY_PRINT |
JSON_UNESCAPED_UNICODE |
JSON_UNESCAPED_SLASHES);C# (.NET)
// System.Text.Json (.NET 5+)
using System.Text.Json;
var options = new JsonSerializerOptions {
WriteIndented = true
};
string pretty = JsonSerializer.Serialize(data, options);
// Newtonsoft.Json (Json.NET)
using Newtonsoft.Json;
string pretty = JsonConvert.SerializeObject(
data, Formatting.Indented);
// Re-indent existing JSON string
string pretty = JToken.Parse(jsonString)
.ToString(Formatting.Indented);JSON.stringify — The Complete Pretty Print Guide for JavaScript
JSON.stringify(value, null, 2) is the standard way to pretty print JSON in JavaScript and Node.js. Most developers use the first and third arguments without fully understanding the second, or the edge cases that silently corrupt data. Here's the complete guide.
Three arguments: value (data to serialize), replacer (which properties to include — pass null to include everything), and space (the indentation that makes the output human-readable).
| space argument | Output format | Best for |
|---|---|---|
| undefined / 0 / null | {"a":1} — no whitespace | Production payloads — smallest file size |
| 2 | 2-space indent per level | APIs, Node.js, most projects (recommended default) |
| 4 | 4-space indent per level | Python, Java, C# — PEP 8 / Java style |
| "\t" | Tab character per level | Projects enforcing tabs via .editorconfig |
| ">> " (any string) | That string as the indent prefix | Custom output — any string up to 10 characters |
| 11+ (number) | Silently clamped to 10 spaces | N/A — never intentional |
All space variants — JavaScript / Node.js
const data = { name: "Alice", age: 30 };
// Minified (no third argument)
JSON.stringify(data);
// {"name":"Alice","age":30}
// 2-space indent — most common
JSON.stringify(data, null, 2);
// {
// "name": "Alice",
// "age": 30
// }
// 4-space indent
JSON.stringify(data, null, 4);
// Tab indent
JSON.stringify(data, null, "\t");
// Node.js: write pretty JSON file
const fs = require('fs');
fs.writeFileSync('out.json',
JSON.stringify(data, null, 2) + '\n');
// Browser console: copy to clipboard
copy(JSON.stringify(data, null, 2));Using the replacer argument
const user = {
id: 1,
name: "Alice",
password: "secret123",
role: "admin"
};
// null replacer — include all properties
JSON.stringify(user, null, 2);
// Array replacer — allowlist specific keys
JSON.stringify(user, ["id", "name"], 2);
// {
// "id": 1,
// "name": "Alice"
// }
// password is excluded
// Function replacer — transform or exclude
JSON.stringify(user, (key, val) => {
if (key === "password") return undefined;
return val;
}, 2);
// password excluded from outputJSON.stringify Edge Cases That Trip Developers Up
| Value type | What JSON.stringify does | How to handle |
|---|---|---|
| undefined (in object) | Key silently omitted — data disappears with no error | Use null if you need the key in output |
| undefined (in array) | Becomes null: [1, undefined, 3] → [1, null, 3] | Filter undefined from arrays before serializing |
| Function | Omitted from objects, null in arrays — silently | Convert to string first: fn.toString() |
| Date object | ISO string: "2024-01-15T00:00:00.000Z" | Expected — parse back with new Date(str) |
| NaN / Infinity | Both become null — silent data change | Validate numbers; use null intentionally for missing values |
| BigInt | Throws TypeError — no JSON equivalent | Convert: id.toString() or use a replacer function |
| Circular reference | Throws TypeError: Converting circular structure | Remove circular refs or use the flatted library |
| Symbol | Silently omitted (same as undefined) | Use string keys — Symbols are not serializable |
Browser Console Shortcut
In Chrome or Firefox DevTools, run copy(JSON.stringify(myObject, null, 2)) to pretty print any JavaScript object and copy it straight to your clipboard — instant, no external tool needed for objects already in scope.
Pretty Printing JSON Arrays
Arrays beautify exactly like objects — each element gets its own indented line. The most common case is an API list response: an array of objects from a /users or /products endpoint. Paste any JSON array (starting with [) into the tool and it beautifies the same way.
Array of objects — API list response (most common)
Before (minified)
[{"id":1,"name":"Alice","role":"admin"},{"id":2,"name":"Bob","role":"user"},{"id":3,"name":"Carol","role":"user"}]After (2-space)
[
{
"id": 1,
"name": "Alice",
"role": "admin"
},
{
"id": 2,
"name": "Bob",
"role": "user"
},
{
"id": 3,
"name": "Carol",
"role": "user"
}
]Simple value array — permissions, tags, or IDs
Before (minified)
["read","write","delete","admin"]
After (2-space)
[ "read", "write", "delete", "admin" ]
| Array type | Beautification behavior | Result shape |
|---|---|---|
| Empty array | Stays on one line — no change | [] |
| Single element | Expands to three lines | [ "value" ] |
| String / number array | One primitive per line, comma after each | [ "a", "b" ] |
| Array of objects | Each object fully expanded inside the array | [ { ... }, { ... } ] |
| Nested arrays | Sub-arrays recursively expanded | [ [ 1, 2 ] ] |
| Mixed-type array | Each element on its own line, type preserved | [ 1, "text", null ] |
JSON Pretty Print in Real Developer Workflows
Experienced developers don't just beautify JSON manually — they automate it at every point in their workflow. Here are the five highest-value integration points:
curl → jq: Instant API Response Beautification
The fastest workflow for reading live API responses from the command line. Pipe directly from curl to jq — no browser, no copy-paste step.
# Prettify any API response instantly curl -s https://api.example.com/users | jq . # With Authorization header curl -s -H "Authorization: Bearer $TOKEN" \ https://api.example.com/users | jq . # Extract the first element and prettify curl -s https://api.example.com/users | jq '.[0]' # Save prettified response to a file curl -s https://api.example.com/users | jq . > response.json
VS Code: Automatic Format on Save
Configure VS Code to auto-format JSON files every time you save. Works for .json, .jsonc, and JSON files in any project.
// Add to settings.json (Ctrl+Shift+P → Open User Settings JSON)
{
"editor.formatOnSave": true,
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
}
}
// Manual shortcut: Alt+Shift+F (Windows/Linux)
// Shift+Option+F (Mac)Git Pre-Commit Hook: Never Commit Unformatted JSON
Auto-format all staged JSON files before every commit. Uses Python's built-in json.tool — zero extra dependencies.
#!/bin/bash
# .git/hooks/pre-commit
# Make executable: chmod +x .git/hooks/pre-commit
git diff --cached --name-only --diff-filter=ACM | \
grep '\.json$' | while read f; do
python3 -m json.tool "$f" > "$f.tmp" && mv "$f.tmp" "$f"
git add "$f"
echo "Formatted: $f"
doneNode.js: Batch Format All JSON Files in a Directory
Prettify every JSON file in a directory tree — useful for cleaning fixtures, test payloads, or config files in bulk.
// format-json.mjs (run: node format-json.mjs)
import { readdir, readFile, writeFile } from 'fs/promises';
import { join, extname } from 'path';
async function formatDir(dir) {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const p = join(dir, entry.name);
if (entry.isDirectory()) {
await formatDir(p);
} else if (extname(entry.name) === '.json') {
const raw = await readFile(p, 'utf8');
const pretty = JSON.stringify(JSON.parse(raw), null, 2);
await writeFile(p, pretty + '\n');
console.log('Formatted:', p);
}
}
}
await formatDir('./src');GitHub Actions: Validate JSON on Every Pull Request
Catch malformed JSON before it reaches code review. Checks all .json files in the repo, excluding node_modules.
# .github/workflows/json-lint.yml
name: Validate JSON
on: [push, pull_request]
jobs:
json-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate all JSON files
run: |
find . -name "*.json" \
! -path "*/node_modules/*" \
! -path "*/.git/*" | while read f; do
python3 -m json.tool "$f" > /dev/null \
|| (echo "Invalid JSON: $f" && exit 1)
doneCommon JSON.stringify Mistakes & How to Fix Them
JSON.stringify has behaviors that surprise even experienced developers — data silently disappears, errors are thrown at runtime, or the output isn't what you expected. Here are the six mistakes to know before they hit you in production:
Circular Reference — TypeError at Runtime
errorconst obj = { name: "Alice" };
obj.self = obj; // circular reference!
JSON.stringify(obj);
// TypeError: Converting circular structure to JSON
// Fix: use the flatted library
import { stringify } from 'flatted';
stringify(obj, null, 2); // handles circular refs safelyFix: Remove the circular reference before serializing, or use the flatted library which handles circular structures. For debugging, use console.dir(obj, { depth: null }) — it handles circular refs natively.
undefined Properties Silently Disappear
warningconst data = { id: 1, name: "Alice", temp: undefined };
JSON.stringify(data, null, 2);
// {
// "id": 1,
// "name": "Alice"
// }
// ← "temp" key is gone — no error thrownFix: If you need the key to appear in output, use null instead of undefined. JSON has no undefined type. Use null to represent "intentionally absent value" in JSON — it serializes and preserves the key.
NaN and Infinity Silently Become null
warningconst data = { score: NaN, limit: Infinity, min: -Infinity };
JSON.stringify(data, null, 2);
// {
// "score": null,
// "limit": null,
// "min": null
// }
// ← silent data change — no error thrownFix: Validate numeric values before serializing. NaN and Infinity are not part of the JSON specification (RFC 8259). Use null for missing numeric values, or strings like "Infinity" if you need to represent them.
Date Objects Lose Their Type
infoconst data = { created: new Date('2024-01-15') };
JSON.stringify(data, null, 2);
// {
// "created": "2024-01-15T00:00:00.000Z"
// }
// ← now a string, not a Date objectFix: Expected behavior — JSON has no Date type. Parse back with: new Date(data.created). For maximum portability, store Unix timestamps (numbers) using .getTime() instead of Date objects.
BigInt Throws TypeError
errorconst data = { userId: 9007199254740993n }; // BigInt
JSON.stringify(data);
// TypeError: Do not know how to serialize a BigInt
// Fix: convert with a replacer function
JSON.stringify(data, (key, val) =>
typeof val === 'bigint' ? val.toString() : val, 2);
// { "userId": "9007199254740993" }Fix: BigInt has no JSON equivalent. Convert to string with .toString() before serializing, or use a replacer function as shown. Note: the receiver must know to parse it back as BigInt, not a regular number.
Double-Stringify: Stringifying a JSON String
warning// Common: API returns an already-stringified JSON string
const apiResponse = '{"name":"Alice","age":30}';
// Mistake: stringify the string (not the object)
JSON.stringify(apiResponse, null, 2);
// "{\"name\":\"Alice\",\"age\":30}" ← escaped string!
// Correct: parse first, then stringify
JSON.stringify(JSON.parse(apiResponse), null, 2);
// {
// "name": "Alice",
// "age": 30
// }Fix: If your data is already a JSON string (typeof data === "string"), parse it first: JSON.parse(data). This tool handles it automatically — paste a double-stringified JSON and it still beautifies correctly.
Why Your JSON Won't Beautify: NDJSON / JSON Lines
If you paste a log file or API stream into a JSON beautifier and get a SyntaxError, you're likely dealing with NDJSON (Newline-Delimited JSON) — also called JSON Lines (.jsonl). NDJSON is one JSON object per line, not a single JSON document. Each line is valid JSON; the file as a whole is not.
NDJSON is not valid JSON. Standard JSON beautifiers (including this one) will reject it with a parse error — that's correct behavior, not a bug. You must process each line individually.
NDJSON (will NOT beautify)
{"id":1,"event":"login","user":"alice"}
{"id":2,"event":"view","user":"bob"}
{"id":3,"event":"click","user":"alice"}
{"id":4,"event":"logout","user":"bob"}Each line is a separate JSON object. Paste all 4 lines into any JSON tool → SyntaxError.
How to handle it — jq
# Pretty print every line independently cat events.jsonl | jq . # Filter NDJSON (events by alice only) cat events.jsonl | jq 'select(.user=="alice")' # Convert NDJSON → JSON array jq -s '.' events.jsonl > array.json # Validate each line individually cat events.jsonl | jq -R 'fromjson?'
Node.js — line-by-line streaming
const readline = require('readline');
const fs = require('fs');
const rl = readline.createInterface({
input: fs.createReadStream('events.jsonl')
});
rl.on('line', (line) => {
if (!line.trim()) return;
const obj = JSON.parse(line);
console.log(JSON.stringify(obj, null, 2));
});Python — line-by-line
import json
with open('events.jsonl') as f:
for line in f:
line = line.strip()
if not line:
continue
obj = json.loads(line)
print(json.dumps(obj, indent=2))
# Online tool workaround:
# Paste ONE line at a time into this tool| Format | Structure | Extension | Beautify with this tool? |
|---|---|---|---|
| JSON | Single document (object or array) | .json | ✓ Yes — paste and press Pretty Print |
| NDJSON / JSON Lines | One JSON object per line | .jsonl / .ndjson | ✗ No — paste one line at a time, or use jq |
| JSON Array | Array of objects [ {...}, {...} ] | .json | ✓ Yes — arrays beautify like any JSON |
| JSON5 | JSON superset with comments, trailing commas | .json5 | ✗ No — use a JSON5 parser first |
JSON Pretty Print vs JSON Formatter: Key Differences
JSON pretty print and JSON formatter both produce indented JSON — but they serve different intents. Pretty print is zero-config: paste, press Ctrl+Enter, done. A JSON formatter gives you configurable control: exact indent size, key sorting, trailing newlines, and strict style guide enforcement. Use pretty print when you need to read JSON quickly; use a formatter when your team has a style guide that must be followed exactly.
JSON minify is the reverse of both: it strips all whitespace to produce the smallest possible payload for production APIs. All three tools produce semantically identical JSON — only the whitespace differs:
| Feature | JSON Pretty Print | JSON Formatter | JSON Minify |
|---|---|---|---|
| Primary goal | Instant readability | Precise formatting control | Smallest file size |
| Adds indentation | ✓ Yes (primary) | ✓ Yes | ✗ No |
| Removes whitespace | ✗ No | ✗ No | ✓ Yes (primary) |
| Configuration required | ✗ None — instant | ✓ Full control | ✗ None |
| Changes data? | ✗ Never | ✗ Never | ✗ Never |
| Auto-beautify on paste | ✓ Yes | ✓ Yes | ✗ No (compacts) |
| Best for | Quick reading & sharing | Exact team style guide | Production payloads |
JSON Won't Beautify? It Has Errors
Pretty printing requires valid JSON. If the tool shows a parse error, fix the JSON first — the JSON Validator gives you the exact line number and character position of every error. Common culprits: trailing commas, single quotes, unquoted keys. Check the JSON Errors Guide for before/after fixes for every common mistake.
Frequently Asked Questions
What is JSON pretty print?expand_more
JSON pretty print is the process of transforming compact or minified JSON into a human-readable format by adding consistent indentation, line breaks, and whitespace. The result is semantically identical to the input — only the whitespace changes, never the data.
What is a JSON beautifier?expand_more
A JSON beautifier is the same as a JSON pretty printer — a tool that transforms compact JSON into an indented, readable format. "Beautify JSON" and "pretty print JSON" are interchangeable terms for the same operation: adding whitespace to make the structure visually clear.
Does pretty printing JSON change the data?expand_more
No. Pretty printing only adds whitespace characters — spaces, tabs, and newlines. Keys, values, data types, and structure remain completely unchanged. The output is semantically equivalent to the input and will parse to the same object in any language.
What is the difference between JSON pretty print and JSON format?expand_more
Pretty print applies default beautification instantly — no configuration needed. A JSON formatter gives you fine control over indentation size, key sorting, and other rules. For quick readability, use pretty print. For precise, configurable output, use a full formatter.
Should I use 2-space or 4-space indentation for JSON?expand_more
2-space indentation is the most common choice for JSON — it is compact, readable, and used by npm, most Node.js projects, and the majority of public APIs. Use 4-space indentation for Python projects or when you prefer more visual separation between nesting levels. Use tab indentation when you want each viewer's editor to control the visual width.
Can I pretty print invalid JSON?expand_more
No. Pretty printing parses the JSON first, then re-serializes it with indentation. If the input has syntax errors, the tool reports the error. Fix the JSON using the JSON Validator (openformatter.com/json-validator) first, then pretty print.
How do I pretty print JSON in VS Code?expand_more
Open the JSON file in VS Code, then press Alt+Shift+F (Windows/Linux) or Shift+Option+F (Mac) to format the document. Alternatively, right-click inside the file and select "Format Document". VS Code's built-in JSON language server handles the formatting.
How do I pretty print JSON in JavaScript?expand_more
Use JSON.stringify(value, null, 2) where 2 is the number of spaces. For tab indentation, use JSON.stringify(value, null, "\t"). This works in the browser console and Node.js.
How do I pretty print JSON on the command line?expand_more
Use jq: pipe JSON to jq with `echo '{"a":1}' | jq .` or `cat data.json | jq .`. On Linux/Mac, Python's built-in json.tool also works: `python3 -m json.tool compact.json`. Both print indented JSON to stdout.
Is this JSON pretty printer free?expand_more
Yes — completely free with no account required. The tool runs entirely in your browser with no usage limits, no paywalls, and no data uploaded. It will always be free.
How do I make JSON human-readable?expand_more
Use a JSON pretty printer: paste your compact JSON and press Pretty Print (or Ctrl+Enter). The tool adds consistent indentation — 2 spaces by default — that makes every nesting level visually distinct. The result is semantically identical to the input but readable by any developer at a glance. For production use, minify again before deploying.
How do I pretty print deeply nested JSON?expand_more
Exactly the same as any JSON — paste it and press Pretty Print. The tool automatically indents each nesting level one step further, no matter how deep: 3 levels, 7 levels, 10 levels. The resulting indentation is the hierarchy map: each level tells you which object owns which field, without counting a single bracket. For interactive collapse/expand navigation of very deep structures, use a JSON viewer.
What does JSON.stringify(data, null, 2) mean?expand_more
JSON.stringify takes three arguments: value (the data to serialize), replacer (which properties to include — null means include all), and space (the indentation). The number 2 means "indent with 2 spaces per level". Use 4 for 4-space indentation, or "\t" for tab indentation. Omitting the third argument (or passing 0) produces minified JSON with no whitespace.
Why does JSON.stringify return undefined?expand_more
JSON.stringify returns undefined (not the string "undefined") when the top-level value is undefined, a function, or a Symbol — these types have no JSON representation. If a property inside an object has an undefined value, the key is silently omitted from the output. If an array element is undefined, it becomes null. To include an absent value in JSON output, use null explicitly instead of undefined.
Can I pretty print a JSON array?expand_more
Yes — paste the JSON array (starting with [) into the tool and press Pretty Print. Arrays beautify exactly like objects: each element gets its own indented line. Empty arrays stay on one line. Arrays of objects expand fully — each object is indented within the array brackets with all its properties on separate lines.
How do I pretty print JSON in the Chrome console?expand_more
In Chrome DevTools console, run: copy(JSON.stringify(myObject, null, 2)) — this pretty prints the object and copies it to your clipboard instantly. Or use console.log(JSON.stringify(myObject, null, 2)) to print it in the console. For API responses, use the Network tab → click the request → "Preview" tab, which auto-renders JSON as a collapsible tree.
Why does my JSON give a SyntaxError when I try to beautify it?expand_more
The most common cause is NDJSON (Newline-Delimited JSON) — log files and API streams often use one JSON object per line, which is not valid as a single JSON document. Paste just one line at a time to beautify it. Other causes: trailing commas, single-quoted strings, unquoted keys, or JavaScript comments. Use the JSON Validator (openformatter.com/json-validator) to pinpoint the exact error location.
Go Deeper
Related JSON Tools
Validate, explore structure, fix errors, and convert JSON — everything around the beautification workflow.
JSON Validator
ToolCheck JSON syntax before beautifying — exact line and character for every error.
JSON Viewer
ToolExplore beautified JSON as a collapsible, navigable tree — perfect for deeply nested structures.
Common JSON Errors
ReferenceEvery JSON syntax error with before/after fix examples — trailing commas, single quotes, unquoted keys.
JSON Minify
ToolThe opposite of pretty print — strip all whitespace to produce the smallest possible JSON for production.
About This Tool
This free JSON beautifier is built and maintained by OpenFormatter — a suite of browser-based developer tools used by engineers worldwide for API debugging, data formatting, and JSON development. All processing is client-side: no accounts, no data uploads, no limits.
Last updated: · Covers JSON pretty printing, indentation styles, nested JSON readability, developer use cases, tool-specific workflows, and code examples for JavaScript, Python, Go, and jq.
Developer Insights
From the Blog
Why JSON Formatting Matters More Than You Think
How proper JSON indentation prevents production bugs, speeds up debugging, and makes code reviews significantly faster.
JSON Beautifier: What It Is and When to Use It
A practical guide to JSON beautification — when to pretty print, what indentation to choose, and how to automate it in your workflow.
YAML vs JSON in 2024: When to Use Each
A definitive guide on choosing the right data serialization format for modern infrastructure and config files.
Part of the JSON Toolkit
Explore All JSON Tools
Free online tools for every JSON task — format, validate, convert, compare, and more.