Copied!
Back
Formatter

JSON Formatter, Validator & Beautifier Online

Paste any JSON to instantly pretty print, minify, or validate it with this free online JSON formatter and validator. Syntax errors are caught and shown with exact line and column numbers per RFC 8259. Customizable indentation (2 spaces, 4 spaces, or tabs), alphabetical key sorting, syntax highlighting, and live stats — size, key count, array count, nesting depth. Everything runs in your browser; no data is uploaded. Works offline, no signup, no ads.

Last updated: April 2026
json-formatter.tool
0 characters
Output will appear here...

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format codified in RFC 8259 and the ECMA-404 standard. It was extracted from JavaScript object literal syntax in the early 2000s by Douglas Crockford, then adopted by every modern programming language as the default format for APIs, configuration files, and data storage. Today it is the dominant data format on the public internet — REST APIs, GraphQL responses, NoSQL databases, infrastructure-as-code, package manifests (package.json, composer.json), and structured logging all use JSON.

JSON's strength is its simplicity. There are exactly six data types — string, number, boolean, null, object, and array — and a tiny grammar that can be parsed by every language without external libraries. Unlike XML, there are no schemas to negotiate, no namespaces, no element-vs-attribute confusion. Unlike CSV, JSON handles nested data and mixed types natively. Unlike YAML, JSON has no indentation rules and no ambiguity around NO, YES, or numbers with leading zeros.

The trade-off is verbosity (lots of quotes and braces) and strictness (any deviation from the spec is a parse error). That strictness is exactly why a JSON formatter and validator is one of the most-used tools in a developer's daily workflow — when an API call breaks, the first question is always: is the JSON even valid?

Valid JSON syntax — the rules nobody remembers

RFC 8259 defines a deceptively simple grammar. The rules that catch developers off-guard:

RuleAllowedNot allowed
Quotes around strings & keys "key" (double quotes only) 'key', key (single quotes or unquoted)
Trailing commas {"a":1,"b":2} {"a":1,"b":2,} (trailing comma)
Comments None — JSON has no comments // comment or /* comment */
Number formats 0, 1.5, -3.14, 1e10, 0.5e-2 01 (leading zero), .5 (leading dot), 1. (trailing dot), NaN, Infinity, +5 (leading plus)
Strings UTF-8 in double quotes; \", \\, \/, \b, \f, \n, \r, \t, \uXXXX Unescaped control characters; raw newlines inside strings; single backslashes
Object keys Any string, must be quoted, must be unique within an object Numeric keys (must be quoted), duplicate keys (technically allowed but parser-dependent)
Top-level value Object {}, array [], string, number, boolean, or null Empty input, multiple top-level values
Whitespace Spaces, tabs, line breaks (anywhere except inside strings) BOM at start of document (some parsers strict)

Common syntax errors and how to fix them

ErrorCauseFix
SyntaxError: Unexpected token } in JSON at position 12 Trailing comma before } or ] Remove the comma. JSON forbids trailing commas, even though JavaScript allows them.
Unexpected token ' in JSON Single quotes around keys or string values Replace all ' with ". JSON requires double quotes.
Unexpected end of JSON input Truncated response, missing closing } or ] Verify the full payload arrived; count brackets. Check Content-Length header for partial reads.
Unexpected token / in JSON Comments (// or /*) inside JSON Remove comments. If you need them, use JSON5 or JSONC and document the dependency.
Bad escaped character Unescaped backslash, e.g. Windows path "C:\path" Double-escape: "C:\\path". JSON treats \ as an escape character.
Number after decimal expected Trailing dot like "value": 1. Remove the trailing dot or add a digit: 1.0.

JSON vs JSON5 vs JSONC vs YAML — when to pick what

"Strict JSON" is great for machines but painful for humans. Several variants relax the rules in trade-off ways. Use this matrix to decide:

FormatCommentsTrailing commasUnquoted keysSingle quotesBest for
JSON (RFC 8259) No No No No API payloads, data interchange. Maximum compatibility.
JSON5 Yes Yes Yes (ES5 identifiers) Yes Human-edited config files. Used by Apple's plist alt and some CLI tools.
JSONC (JSON with Comments) Yes Yes No No VS Code config (tsconfig.json, settings.json). Comments are the killer feature.
YAML Yes N/A (no commas needed) Yes Yes Long config files (Kubernetes, GitHub Actions, Docker Compose). Indentation-sensitive.

This formatter accepts strict JSON (RFC 8259). For JSON5 or JSONC, strip the comments and trailing commas first, then format. For YAML, use our YAML to JSON converter to switch formats.

Working with JSON in 8 programming languages

Every modern language ships with a built-in JSON parser. Here are the canonical idioms — paste these into your project as a starting point.

JavaScript / TypeScript

javascript
// Parse string → object
const data = JSON.parse('{"name":"Anees","age":30}');

// Stringify object → string (indent 2 spaces)
const json = JSON.stringify(data, null, 2);

// Stringify with custom replacer (drop sensitive fields)
const safe = JSON.stringify(data, (key, val) =>
  key === 'password' ? undefined : val
);

// Parse safely with try/catch
try { JSON.parse(input); } catch (e) { /* malformed */ }

Python

python
import json

# String → dict
data = json.loads('{"name":"Anees","age":30}')

# Dict → string (indent=2 for pretty print)
text = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)

# File-based
with open('data.json') as f: data = json.load(f)
with open('out.json', 'w') as f: json.dump(data, f, indent=2)

PHP

php
// String → assoc array (true = associative; false = stdClass)
$data = json_decode('{"name":"Anees","age":30}', true);

// Array → string (JSON_PRETTY_PRINT for indent)
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Check for parse errors
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

Java (Jackson)

java
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

// String → POJO
User u = mapper.readValue(jsonString, User.class);

// POJO → pretty-printed string
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(u);

// Generic parsing without a class
JsonNode root = mapper.readTree(jsonString);
String name = root.get("name").asText();

Go

go
import "encoding/json"

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// Bytes → struct
var u User
json.Unmarshal([]byte(`{"name":"Anees","age":30}`), &u)

// Struct → indented bytes
out, _ := json.MarshalIndent(u, "", "  ")

Rust (serde_json)

rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User { name: String, age: u32 }

let u: User = serde_json::from_str(r#"{"name":"Anees","age":30}"#)?;
let pretty = serde_json::to_string_pretty(&u)?;

Ruby

ruby
require 'json'

# String → hash
data = JSON.parse('{"name":"Anees","age":30}')

# Hash → pretty-printed string
text = JSON.pretty_generate(data)

# Strict: raise on duplicate keys
JSON.parse(input, allow_duplicate_keys: false)

Bash (jq)

bash
# Pretty print
cat data.json | jq

# Minify
cat data.json | jq -c

# Extract a field
curl -s api.example.com | jq -r '.users[0].name'

# Validate (exit code 0 = valid, non-zero = invalid)
jq empty data.json

If your toolchain isn't here, the principle is the same: parse to a native object/dictionary, manipulate it, serialize back. Avoid hand-crafting JSON with string concatenation — that's how you get unescaped quotes and security bugs.

Pretty print, minify, and key sorting — when to use each

Pretty printing (formatting)

Adds whitespace, line breaks, and indentation so humans can read the structure. Use during development, debugging, code review, log inspection, and when storing JSON in version control (diff readability). Default indent: 2 spaces in JS/Python ecosystems, 4 spaces in some style guides. Tabs work but vary across editors.

Minification

Strips all unnecessary whitespace — output is one long line. Use for HTTP responses (gzip already handles whitespace, but minified JSON is smaller before compression too), embedded JSON in HTML attributes, JWTs, cache values, and anywhere bandwidth or storage matters. Typical size reduction: 20–40% before gzip.

Alphabetical key sorting

Reorders object keys lexically. Use when you need deterministic output — content-addressable storage (hash the JSON), config diffs (so reordered keys don't show as changes), and HTTP signature schemes (e.g. Stripe webhooks, AWS SigV4) that require canonical JSON. Don't sort if your downstream consumer cares about key order (e.g. some legacy XML-to-JSON systems).

JSON spec note: RFC 8259 says object key order is not significant — parsers may return keys in any order. In practice, most modern parsers (V8, CPython 3.7+, Go) preserve insertion order. Don't depend on order across languages or runtimes.

Performance — handling large JSON responsibly

JSON parsing is O(n) in payload size, but the constant factor is real. A 100MB JSON file can take 5+ seconds to parse and consume 5–10× its size in memory due to object overhead. Strategies for big payloads:

  • Stream-parse instead of JSON.parse. Libraries: stream-json (Node), ijson (Python), jackson-core Streaming API (Java), encoding/json Decoder (Go). They emit events for each token, never building the full object tree in memory.
  • Use NDJSON / JSON Lines for log-like data — one JSON object per line. Parse line by line, process incrementally. Used by Elasticsearch, Splunk, and most log shippers.
  • Switch to a binary format when JSON's overhead becomes the bottleneck. CBOR, MessagePack, or Protocol Buffers can be 30–70% smaller and 2–5× faster to parse, with the trade-off of losing human-readability.
  • Use JSON.parse with a reviver in JavaScript to filter/transform values during parse rather than after. Saves a full second pass over deeply-nested data.
  • Avoid JSON for binary data. Base64-encoding a 1MB image into JSON makes it 1.33MB. Use multipart uploads or binary-safe formats instead.

JSON Schema — validating structure beyond syntax

Valid JSON syntaxvalid JSON content. A formatter tells you the brackets balance; a schema tells you the data has the right shape. JSON Schema is the de-facto standard for declaring "this object must have a name string and an age integer 0–150."

json-schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "email"],
  "properties": {
    "name":  { "type": "string", "minLength": 1, "maxLength": 100 },
    "email": { "type": "string", "format": "email" },
    "age":   { "type": "integer", "minimum": 0, "maximum": 150 }
  },
  "additionalProperties": false
}

Use schema validation at API boundaries: Express middleware (ajv), FastAPI auto-validates Pydantic models, gRPC has Protobuf, OpenAPI 3.x is mostly JSON Schema. The investment pays off when you stop debugging "why did my API receive null?" — your schema rejected the bad payload before your handler ran.

JSON prettier, pretty JSON, prettier JSON — what users actually mean

"JSON prettier", "pretty JSON", "prettier JSON", "json pretty" — Google sees these as a single intent: take this JSON blob, indent it, and make it readable. Some people confuse the noun-form with the JavaScript code formatter Prettier; the two are unrelated. The tool above does what most "JSON prettier" searches actually want: paste JSON in, get indented JSON out, with brackets aligned, keys color-coded, and syntax errors highlighted at the offending line. No installation, no Node project, no npx command — open the page and paste.

Pretty JSON output — 2 spaces, 4 spaces, or tabs?

RFC 8259 doesn't specify whitespace, so any indentation is "pretty". The de-facto conventions: 2 spaces in JavaScript and TypeScript codebases (matches Prettier's default), 4 spaces in Python and Java (matches PEP 8 / Google Java style), tabs in older Go and shell-heavy projects. Pick one per repo — toggling between them creates noise in version-control diffs without changing any data. The formatter above defaults to 2 spaces with a toggle for 4 and tabs.

JSON pretty print in JavaScript, Python, and PHP — one-liners

Three native one-liners that match the formatter's output:

  • JavaScript: JSON.stringify(obj, null, 2) — the third argument is the indent count.
  • Python: json.dumps(obj, indent=2) — same idea, different argument name.
  • PHP: json_encode($arr, JSON_PRETTY_PRINT) — flag-based, fixed at 4 spaces.

For larger automation — pretty-printing 1000+ files in CI, sorting keys, removing trailing commas — pair this tool's output with jq '.' at the CLI, or process the output through the JSON to CSV converter if you need tabular data instead.

Free JSON formatter without ads — what to look for

Most "free formatter" search results route through ad-heavy pages that load 10+ third-party scripts before they format your JSON. Some POST your input to a backend for "validation" — meaning your JSON (which often contains tokens, IDs, internal field names) sits in their server logs forever. The formatter above is fully client-side: open DevTools → Network, paste JSON, click format — zero requests fire. It works offline. View source any time and search for JSON.parse to confirm the parser is the browser's native one, not a remote API.

JSON formatter and SEO best practices

  • Use JSON-LD for structured data. Google's preferred format for rich-result eligibility (FAQPage, Product, Article, BreadcrumbList). Embed inside <script type="application/ld+json">. Use our meta tag generator to scaffold the markup.
  • Keep your application/json Content-Type header correct. Browsers and crawlers behave differently with text/plain or missing types — Cloudflare and many CDNs apply caching/compression rules based on it.
  • Don't index API responses. Add X-Robots-Tag: noindex to /api/* endpoints — JSON in search results looks broken and dilutes your domain's quality score.
  • Use UTF-8 with ensure_ascii=false in Python (or equivalent) for international content. Reduces payload size and avoids escape-encoding artifacts in your indexed snippets.

How to use the JSON formatter

Whether you're debugging a malformed API response or reviewing a config file, the workflow is the same: paste, format, fix any errors flagged, and copy. The formatter never sends data to a server, so even production payloads with sensitive customer info can be pasted safely.

Common JSON mistakes to avoid

Frequently Asked Questions

What is JSON?
JSON (JavaScript Object Notation) is a lightweight, human-readable text format for storing and transmitting data. It consists of key-value pairs in objects {"key": "value"} and ordered arrays [1, 2, 3]. JSON supports six data types: string, number, boolean, null, object, and array. It's the dominant data format for REST APIs, configuration files, and database storage.
What are the most common JSON errors?
The top JSON errors are:
1. Single quotes — JSON requires double quotes around keys and strings. 'name'"name"
2. Trailing commas{"a": 1,} is invalid. Remove the comma after the last item.
3. Unquoted keys{name: "John"} is JavaScript, not JSON. Keys must be quoted.
4. Comments — JSON does not support // or /* */.
5. Undefined/NaN/Infinity — these JavaScript values are not valid JSON.
What is the difference between JSON pretty print and minify?
Pretty print adds indentation and line breaks, making JSON readable for humans. Use it for debugging, config files, and documentation. Minify removes all whitespace and newlines, reducing file size for network transmission. Minified JSON can be 20–30% smaller. Both produce equivalent data — only formatting differs.
Does JSON support comments?
No. Standard JSON (RFC 8259) does not support comments. This is intentional — JSON was designed as a data format, not a configuration format. If you need comments in config files, consider JSONC (JSON with Comments, used by VS Code), YAML, or TOML instead.
How do I parse JSON in JavaScript, Python, and Go?
JavaScript: const obj = JSON.parse(jsonString); — and serialize with JSON.stringify(obj, null, 2)
Python: import json; obj = json.loads(json_string) — serialize: json.dumps(obj, indent=2)
Go: import "encoding/json"; json.Unmarshal([]byte(jsonString), &obj)
PHP: $obj = json_decode($jsonString, true);
Is my JSON data safe to paste here?
Yes. All processing is done entirely in your browser using JavaScript's built-in JSON.parse() and JSON.stringify() APIs. No data is ever sent to a server. The tool works fully offline. We strongly recommend not pasting production secrets or API keys into any online tool — as a general security practice.

Browse all 50 free developer tools

All tools run in your browser, no signup required, nothing sent to a server.