JSON Formatter

Our JSON formatter is a fast, free online tool for developers to format, validate, and minify JSON data. Paste your JSON and instantly see it pretty-printed with syntax highlighting. The validator pinpoints exact error locations with line numbers, making it easy to fix malformed JSON. Supports 2-space, 4-space, and tab indentation, plus one-click minification for production use. All processing happens in your browser — your JSON, including any sensitive payloads, never leaves the page.

star 4.9
auto_awesome AI
New

JSON Formatter calculator

info Paste JSON to format
0 lines 0 B 0 keys depth 0

lightbulb Tips

  • JSON keys must use double quotes
  • Trailing commas are not valid JSON
  • Use 2-space indent for most projects
  • Minify JSON for API payloads

How to Format, Validate and Minify JSON in 3 Steps

content_paste

Paste JSON

Paste your raw or messy JSON into the input editor. Supports any valid (or invalid) JSON text.

code

Format or Minify

Click Format to pretty-print with your chosen indentation, or Minify to compress. Errors are highlighted automatically.

content_copy

Copy Result

Click the Copy button to copy formatted JSON to your clipboard. Use in your code, API requests, or config files.

bug_report

Fix Errors

If JSON is invalid, the error message shows the exact line and position. Fix the issue and re-format.

The Formula

JSON formatting works by parsing the raw JSON string into a JavaScript object (which validates it), then re-serializing it with proper indentation. If parsing fails, the error message includes the position of the syntax error. Minification removes all whitespace by using no indentation.

JSON.parse(input) → JSON.stringify(parsed, null, indent)

lightbulb Variables Explained

  • input Raw JSON string to be formatted
  • JSON.parse() Validates and parses JSON — throws error if invalid
  • JSON.stringify() Converts parsed object back to formatted string
  • indent Number of spaces (2 or 4) or tab character for indentation

tips_and_updates Pro Tips

1

Use 2-space indentation for compact files, 4-space for readability

2

Minify JSON before sending in API requests to reduce payload size

3

Common errors: trailing commas, single quotes, and unquoted keys are not valid JSON

4

Use Ctrl+A to select all, then paste — the formatter handles any whitespace

5

JSON keys must always be double-quoted strings — {key: value} is not valid JSON

6

Arrays and objects can be empty: [] and {} are valid JSON

7

null, true, false are valid JSON values — but undefined and NaN are not

8

RFC 8259 requires UTF-8 encoding — escape non-ASCII characters with \uXXXX if your transport is ASCII-only

9

Sort object keys alphabetically before diffing two JSON files for cleaner change sets

10

For very large files, prefer streaming parsers (jq, ijson, Jackson Streaming) over JSON.parse

Format, validate, and minify JSON instantly with syntax highlighting, error line numbers, and one-click copy. All processing runs in your browser — paste API responses, JWT payloads, or sensitive config without it ever leaving your device. Below: how the formatter works, the JSON spec it validates against (RFC 8259 / ECMA-404), and deep dives on JSON Schema, JSONPath, JSON Lines, JSON5, and security pitfalls every developer should know.

JSON Formatter Online: Pretty Print and Beautify Any JSON

Paste compact, minified, or messy JSON and get perfectly indented output instantly. The formatter parses your JSON with the browser's native JSON.parse (per ECMA-404), preserves Unicode characters, and re-emits with your chosen indent — 2 spaces (npm and prettier default), 4 spaces, or tab. Nested objects and arrays are correctly indented at every depth. Keys, strings, numbers, booleans, and null get distinct syntax-highlighting colors so you can scan structure at a glance. The 'beautifier' label is interchangeable with 'formatter' or 'pretty printer' — all describe the same operation: producing human-readable JSON from compact input.

How to Validate JSON: RFC 8259 Compliance and Common Errors

Validation runs as you type. If your JSON fails to parse, the formatter shows the exact line, column, and what the parser expected. Validation is strict per RFC 8259 (the IETF Internet Standard) and ECMA-404 — no comments, no trailing commas, no single quotes, no unquoted keys, no NaN, no Infinity, no undefined. Top-level value can be any JSON value (object, array, string, number, true, false, null). For UTF-8 encoded input, the formatter accepts the full Unicode character set; ASCII-only environments should use \uXXXX escapes. Common errors and fixes: trailing comma after the last array/object element (remove it), single quotes around keys or strings (replace with double quotes), missing closing brace or bracket (the error column points near the truncation), and unescaped control characters in strings (escape with \n, \t, \\).

JSON Minifier: Reduce Payload Size for APIs and Production

Minification strips all insignificant whitespace — spaces between tokens, indentation, and newlines — leaving the most compact possible representation. Typical savings are 20–60% depending on how much your source JSON was indented. Use minified JSON for: REST/GraphQL API responses, WebSocket messages, JWT payloads, SaaS config blobs, embedded data attributes in HTML. Keep formatted (pretty-printed) JSON for: source-controlled config files, fixtures and snapshots in tests, and human-edited documents. Minified JSON is still 100% standard JSON — any compliant parser accepts it. The minifier here preserves data exactly: no key reordering, no value coercion, no precision loss on numbers within IEEE 754 double range.

JSON Schema Validation: Validate Types, Required Fields & Enums

Pure JSON syntax validation only checks that the document parses. JSON Schema validates the document's shape — that 'email' is a string, 'age' is an integer 0–150, 'role' is one of ['admin', 'user', 'guest']. A schema is itself a JSON document describing the constraints; instances are validated against it. Common keywords: type, required, properties, items, enum, pattern (regex), minimum/maximum, minLength/maxLength, format (email, date-time, uri). Reference implementations: Ajv (JavaScript, fastest), jsonschema (Python), networknt/json-schema-validator (Java), justinrainbow/json-schema (PHP). Schema validation catches a huge class of bugs at the API boundary: missing required fields, wrong types, out-of-range values, malformed dates. OpenAPI 3.x specs use JSON Schema for request/response validation.

JSONPath Tutorial: Query and Extract Values from Nested JSON

JSONPath is to JSON what XPath is to XML — a query language for navigating and extracting from nested JSON. Syntax: $ (root), . (child), .. (recursive descent), [n] (array index), [start:end] (slice), [?(expression)] (filter), * (wildcard). Examples on a typical store JSON: $.store.book[0].title gets the first book's title; $..author returns every author across the document; $.store.book[?(@.price < 10)] filters books cheaper than 10; $.store..price[*] flattens all prices. Tools: jq (slightly different syntax but the same capabilities, dominant in shell scripting), Postman test scripts, JMESPath (AWS CLI's --query), and JSONPath libraries in every major language.

JSON Lines (JSONL): Newline-Delimited JSON for Logs and Streams

JSON Lines (jsonlines.org), also known as NDJSON or LDJSON, is a format where each line is a complete JSON value. The file as a whole is not valid JSON — but each line individually is. Used heavily for log streaming (Loki, Splunk HEC, Vector), ETL pipelines, machine learning training data (OpenAI fine-tuning files), and any append-only data flow. Advantages: streaming-friendly (parse one record at a time, constant memory), append-only (just write the next line), grep-able and awk-able with standard Unix tools. File extensions: .jsonl, .ndjson. Convert from a JSON array with `jq -c '.[]'`; convert to a JSON array with `jq -s` (slurp). BigQuery, Athena, Snowflake, and most modern data warehouses ingest NDJSON natively.

JSON5 vs JSON: When to Use Each Format Safely

JSON5 (json5.org) extends JSON with developer conveniences: comments (// and /* */), trailing commas, single-quoted strings, unquoted keys, multi-line strings (with backslash continuation), hexadecimal numbers, and IEEE 754 special values (NaN, Infinity). It is NOT compatible with JSON.parse — you need a JSON5 parser (json5 npm package, PyJson5). Use JSON5 for human-edited config files where comments are valuable: babel.config.json5, some build tool configs, .vscode/settings.json (which uses JSONC, a similar JSON-with-comments dialect). Stick to strict JSON for: HTTP APIs, data interchange, storage formats, and anything machine-generated. Mixing the two confuses tooling — pick one per file and stick with it.

Common JSON Errors: Trailing Commas, Single Quotes & Encoding

The most frequent JSON parse errors and fixes: (1) Trailing comma after the last element — `{"a":1,}` or `[1,2,3,]` — remove the dangling comma. (2) Single quotes on keys or string values — `{'name':'Alice'}` — must be double quotes. (3) Unquoted keys — `{name:"Alice"}` — quote them. (4) Comments using // or /* */ — strict JSON does not allow them; strip or switch to JSON5/JSONC. (5) JavaScript values that don't exist in JSON — undefined, NaN, Infinity, functions — replace with null or remove. (6) Truncated input — the parser usually points to the line where it ran out of expected content. (7) BOM (byte-order mark) at the start of a UTF-8 file — most parsers reject it; strip with `sed -i '1s/^\xEF\xBB\xBF//'`. (8) Mixed tabs and spaces don't break parsing but break diffs — pick one indent style.

JSON Security: Prototype Pollution, Eval and Safe Parsing

Three categories of JSON-related vulnerabilities every developer should understand. (1) Prototype pollution: merging untrusted JSON into an existing object can pollute Object.prototype if the input contains __proto__, constructor, or prototype keys — affecting every object in the runtime. Use Object.create(null), structuredClone, or libraries like lodash's defaultsDeep that explicitly block these keys. (2) Never use eval() to parse JSON — eval executes any JavaScript, while JSON.parse is sandboxed. The 'eval is faster' myth was debunked years ago. (3) Re-serialization gotchas: JSON.stringify silently omits functions, undefined, and Symbol values from objects (converts to null in arrays). It also throws on circular references and BigInt by default. Validate untrusted JSON with JSON Schema before processing, set a max body size on your API, and use Content-Type checks to reject non-JSON inputs early. OWASP's REST Security Cheat Sheet covers the full picture.

Convert JSON to YAML, CSV and XML: Format Conversion Guide

JSON ↔ YAML is the most lossless conversion — both support nested objects/arrays. Watch out for YAML's automatic type coercion (yes/no/on/off become booleans, unquoted numbers stay numbers, the literal string 'null' becomes null) — quote ambiguous values. Tools: js-yaml (npm), PyYAML, yq. JSON → CSV requires flattening nested structure — works best for arrays of flat objects. Pick a strategy for nested values: stringify (write as JSON in a cell) or dot-notation columns (`address.city`, `address.zip`). Tools: csvkit's in2csv, pandas pd.json_normalize, json2csv (npm). JSON → XML is straightforward for tree structures but loses the array vs object distinction — XML siblings could be either. Watch for invalid XML element names (can't start with digits, can't contain spaces). Tools: xml-js, xmltodict (Python). For all conversions, decide upfront whether you preserve type information or flatten everything to strings.

Working with Large JSON Files: Streaming Parsers & Memory Tips

JSON.parse loads the entire document into memory — fine for typical API responses, problematic for files over a few hundred MB. Streaming parsers process one token (or one record) at a time, holding constant memory regardless of file size. JavaScript: stream-json or oboe.js for SAX-style parsing. Python: ijson for incremental parsing, or convert to JSON Lines first and read line-by-line. Java: Jackson Streaming API (JsonParser). Shell: jq processes streaming JSON via --stream. For files generated as JSON arrays of records, consider switching the producer to emit JSON Lines instead — every downstream consumer benefits. When you must handle a huge JSON array in memory, prefer iterating and discarding records rather than building a parallel data structure. Watch heap size, set --max-old-space-size in Node, and profile before optimizing.

JSON Formatter Cheat Sheet: Indent, Sort Keys, Diff & Escape

Quick reference for everyday JSON tasks. Indent: prettier and npm default to 2 spaces; pick 4 for enterprise codebases that already use 4-space indent across languages; tabs are valid but rare in JSON. Sort keys (for cleaner diffs): JSON.stringify(obj, Object.keys(obj).sort(), 2) for shallow objects; jq --sort-keys for deep recursion; Python json.dumps(obj, sort_keys=True). Diff two JSON files: jq --sort-keys both files, then run regular diff; or use json-diff (npm), DeepDiff (Python), VS Code's built-in JSON-aware compare. Escape sequences in strings: \" (double quote), \\ (backslash), \/ (forward slash, optional), \b (backspace), \f (form feed), \n (newline), \r (carriage return), \t (tab), \uXXXX (Unicode code point). Numbers: JSON allows decimals and exponents (1.5e3) but no leading zeros (0123 is invalid) and no trailing decimal point (1. is invalid). Strings must be double-quoted — single quotes are JSON5 only.

code

Embed this JSON Formatter on your site

Free for any site. Copy the snippet below and paste into your HTML — no attribution required beyond the built-in credit link.

<iframe src="https://calculators.im/embed/json-formatter" width="100%" height="720" style="border:0;max-width:100%;" loading="lazy" title="JSON Formatter by Calculators.im"></iframe>
<p style="font-size:12px;text-align:center;color:#64748b;margin-top:6px;">Powered by <a href="https://calculators.im/json-formatter?utm_source=embed&utm_medium=snippet&utm_campaign=json-formatter">JSON Formatter</a> by Calculators.im</p>
open_in_new Preview embed Auto-resizing iframe. Mobile responsive. Works with WordPress, Ghost, Webflow, and plain HTML.

Frequently Asked Questions

sell

Tags