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:
| Rule | Allowed | Not 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
| Error | Cause | Fix |
|---|---|---|
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:
| Format | Comments | Trailing commas | Unquoted keys | Single quotes | Best 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
// 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
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
// 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)
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
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)
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
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)
# 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).
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-coreStreaming API (Java),encoding/jsonDecoder (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.parsewith areviverin 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 syntax ≠ valid 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."
{
"$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/jsonContent-Type header correct. Browsers and crawlers behave differently withtext/plainor missing types — Cloudflare and many CDNs apply caching/compression rules based on it. - Don't index API responses. Add
X-Robots-Tag: noindexto/api/*endpoints — JSON in search results looks broken and dilutes your domain's quality score. - Use UTF-8 with
ensure_ascii=falsein Python (or equivalent) for international content. Reduces payload size and avoids escape-encoding artifacts in your indexed snippets.