The Complete Guide to JSON
JSON (JavaScript Object Notation) is the text format that most of the modern web runs on. It is how a React app talks to its backend, how a webhook describes an event, how package.json declares dependencies, and how a log pipeline ships structured records. If you write software in 2026, you read and write JSON every day — which is exactly why a solid JSON guide pays for itself: the format is small enough to learn in an afternoon, but its strictness catches people out constantly. A trailing comma, a single quote, or an unquoted key will break a parse, and the error messages are rarely helpful about where the real problem is.
This guide covers the JSON format end to end. You will find the complete syntax rules and the six valid data types, a realistic example, how the JSON data format compares to XML and YAML, the syntax errors that account for most parse failures and how to spot them fast, escape characters, when to minify versus beautify, and how JSON behaves in real APIs. Along the way I will point you at the browser-based tools that make each of these tasks quicker.
One note before we start: every tool linked here runs entirely in your browser. Your JSON is never uploaded to a server, which matters when the payload you are debugging contains an access token, a customer record, or an internal API shape you would rather not paste into someone else's backend.
What JSON Is
JSON is a language-independent text format for representing structured data. Douglas Crockford specified it in the early 2000s, drawing the syntax from JavaScript object literals, and it is now standardised as ECMA-404 and RFC 8259. The name mentions JavaScript, but JSON is not JavaScript, and every serious language ships a parser for it.
Two properties explain its dominance. First, it is trivial to read: a developer with no documentation can usually infer what a JSON payload means at a glance. Second, it maps almost directly onto the native data structures of nearly every language — dictionaries and lists in Python, maps and slices in Go, objects and arrays in JavaScript — so deserialising it takes one function call rather than a schema compiler.
JSON is also strict. That strictness is a feature: because there is no ambiguity in the grammar, two independent parsers will agree on what a document means. It is also the source of nearly every frustration people have with the format, so it is worth learning the rules properly.
JSON Syntax Rules
A JSON document is a single value. In practice that value is almost always an object or an array, but a bare string, number, boolean, or null is legal JSON under RFC 8259.
Objects
An object is an unordered collection of key-value pairs wrapped in curly braces:
- Keys must be strings in double quotes.
{name: "Ada"}and{'name': 'Ada'}are both invalid. - A colon separates each key from its value, and commas separate the pairs.
- No comma is allowed after the final pair.
- Duplicate keys are not forbidden by the grammar, but behaviour is undefined — most parsers keep the last one. Never rely on it.
Arrays
An array is an ordered list wrapped in square brackets, with values separated by commas and no trailing comma. Arrays may be heterogeneous — [1, "two", null, {"three": 3}] is valid — though in practice you should keep them uniform so consumers can process them in a loop.
Valid Data Types
JSON has exactly six types:
- String — double-quoted Unicode text. Single quotes are never valid.
- Number — a decimal number, optionally with a fraction and an exponent. There is no separate integer type, no leading
+, no leading zeros (01is invalid), and noNaNorInfinity. - Boolean — lowercase
trueorfalse. - null — lowercase, the explicit empty value.
- Array — ordered list.
- Object — key-value collection.
Notably absent: dates, binary data, and comments. Dates are conventionally encoded as ISO 8601 strings ("2026-08-06T14:30:00Z"), binary data as Base64 strings. Both conventions live in your application code, not in the format.
A Real Example
{
"id": "usr_8Kq2",
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true,
"loginCount": 42,
"lastLogin": "2026-08-06T14:30:00Z",
"deletedAt": null,
"roles": ["admin", "billing"],
"preferences": {
"theme": "dark",
"notifications": { "email": true, "sms": false }
},
"sessions": [
{ "ip": "10.0.0.4", "device": "macbook-pro" },
{ "ip": "10.0.0.9", "device": "iphone" }
]
}
That single document shows every type in play: strings, a number, booleans, null, a flat array, a nested object, and an array of objects. Nesting is unlimited in the spec, though parsers impose practical depth limits to guard against stack exhaustion.
When a payload gets deeper than this, reading raw text stops working. A JSON Tree Viewer turns the document into a collapsible tree so you can fold away the branches you do not care about and drill into the one you do — far faster than scrolling a 4,000-line API response hunting for one nested field.
How JSON Compares to XML and YAML
XML was the default interchange format before JSON took over, and the trade-off is straightforward. XML is more verbose — every field costs an opening and closing tag — and its parsers are measurably slower, commonly in the range of two to five times, because they must handle namespaces, attributes, entities, and a document object model. JSON carries less overhead on the wire and deserialises straight into native types.
XML still earns its place where its extra machinery is the point: mature schema validation via XSD, XPath and XSLT for querying and transforming documents, attributes and mixed content for marking up prose, and entrenched enterprise systems such as SOAP services and financial messaging standards. If you need a contract that a third party can validate against before sending you anything, XML's tooling is older and deeper — though JSON Schema has closed much of that gap.
YAML is a superset of JSON aimed at humans. It drops braces and quotes, uses indentation for structure, and — crucially — supports comments, which is why Kubernetes manifests, CI pipelines, and Docker Compose files use it. The cost is ambiguity: YAML's implicit typing has historically turned NO into a boolean and version strings into numbers, and indentation errors are easy to make and hard to see. The rule of thumb holds up well: YAML for files people hand-edit, JSON for data machines exchange.
Both comparisons deserve their own detailed treatment, and each has its own post in this cluster. For now the orientation is enough: JSON is the default for APIs, and you need a specific reason to choose otherwise.
Common JSON Syntax Errors
Most JSON failures come from a handful of mistakes, and nearly all of them are people writing JavaScript or Python by muscle memory instead of JSON.
Trailing commas. {"a": 1, "b": 2,} is invalid. JavaScript, Python, and most modern languages permit trailing commas in literals; JSON does not. This is the single most common cause of Unexpected token } errors.
Unquoted keys. {name: "Ada"} is a valid JavaScript object literal and invalid JSON. Every key needs double quotes.
Single-quoted strings. {'name': 'Ada'} is invalid for the same reason — JSON strings are double-quoted, always. This bites hardest when someone pastes a Python dict and expects it to parse.
Comments. // like this or /* like this */ will be rejected. There is no comment syntax in JSON. If you need annotation, use JSON5 or JSONC in your editor and strip the comments before parsing, or move to YAML.
Python and JavaScript literals. True, False, None, undefined, NaN, and Infinity are all invalid. JSON wants lowercase true, false, and null.
Unescaped characters inside strings. A raw double quote, backslash, or literal newline inside a string terminates or corrupts it. See the next section.
Mismatched or missing brackets. In a long document this is genuinely hard to find by eye, especially when the parser reports a position hundreds of lines away from the actual mistake — the error surfaces where the structure finally becomes impossible, not where you dropped the brace.
The practical fix for all of these is to stop reading character by character and let a parser tell you. A JSON Validator checks the document against the spec and reports the line and column of the first failure, which usually makes the cause obvious even when the reported location is slightly downstream of it. That takes seconds, versus the several minutes it takes to eyeball a config file for a comma.
JSON Escape Characters
Inside a JSON string, the backslash starts an escape sequence. The valid escapes are:
\"— double quote\\— backslash\/— forward slash (optional, but useful when embedding JSON in a<script>tag, where</can end the element early)\b— backspace\f— form feed\n— newline\r— carriage return\t— tab\uXXXX— any Unicode code point, as four hex digits
Anything else after a backslash is a syntax error — \x41 and \' are both invalid, even though many languages accept them.
Two rules cause most escaping bugs. First, control characters below U+0020 must be escaped; you cannot put a literal newline inside a JSON string, only \n. Second, characters outside the Basic Multilingual Plane — emoji, for instance — need a surrogate pair when written as \u escapes: the grinning face emoji is written as \uD83D\uDE00, two escapes rather than one. Most of the time you should let your language's serialiser handle this rather than writing escapes by hand.
Escaping gets genuinely painful when you nest JSON inside JSON — a stringified payload stored in a database column, or a webhook body carried as a string field. Every quote in the inner document gets a backslash, and reading the result unaided is miserable. Pasting it into a formatter that unescapes and re-indents it is the fastest way back to something legible.
Minify or Beautify: When to Use Each
The two operations serve opposite audiences.
Beautified (or "pretty-printed") JSON adds indentation and line breaks. Use it whenever a human reads or edits the file: committed config, fixtures, documentation examples, and anything under version control — indentation makes diffs line-oriented and reviewable rather than a single monstrous changed line. A JSON Formatter handles this instantly, and it doubles as a validator since it cannot format what it cannot parse.
Minified JSON strips every byte of insignificant whitespace. Use it everywhere the consumer is a machine: API responses, message queue payloads, log lines, embedded config in a JS bundle, and browser local storage. On a deeply nested document, whitespace can account for a meaningful share of the payload — sometimes 20% or more — and while gzip already compresses repeated whitespace well, you still pay to produce, transmit, and parse it. Run a JSON Minifier as a build step for any JSON you ship.
Minifying never changes what the document means. Whitespace between JSON tokens is insignificant; whitespace inside a string is data and is preserved. Round-tripping a document through minify and beautify gives you back semantically identical JSON, so this is a safe transformation to automate.
JSON in APIs
REST APIs standardised on JSON for a reason: it is compact, self-describing, and parses natively in the browser. A few practices separate APIs that are pleasant to consume from ones that are not.
Set the right content type. Send Content-Type: application/json on requests with a body and on responses. Some frameworks silently fall back to form encoding or text/plain when you forget, and the client-side parse then fails for no obvious reason.
Keep the response shape stable. If a field is a string, it should always be a string — not null sometimes and "" others, not a number when the value is numeric. Type-flapping fields are the most common source of client crashes. Prefer explicit null over omitting a key, so consumers can distinguish "no value" from "field not present".
Return errors as JSON too. An API that returns JSON on success and an HTML error page on failure forces every client to write defensive parsing. Standardise on a shape — RFC 9457 problem details is a reasonable choice — and use it for every non-2xx response.
Watch the payload size. Paginate collections, and do not return every column of every row because it was easy. Large JSON responses cost bandwidth, parse time, and memory on the client.
Never eval JSON. Use JSON.parse, which will not execute code. Also be aware that JavaScript numbers are IEEE 754 doubles, so integer IDs above 2^53 lose precision silently — send large IDs as strings, or use a parser with BigInt support.
The debugging workflow around all this is simple. Copy the response from your network tab, drop it into the JSON Formatter to make it readable, switch to the tree viewer when the structure is deep enough that indentation alone is not helping, and reach for the validator when a payload is being rejected and you need to know exactly where the grammar broke. Because all of it runs client-side, you can do this with production responses containing real customer data or bearer tokens without that data leaving your machine — which is not something you can say about most online JSON tools.
Conclusion
JSON is deliberately small: one value per document, six data types, double-quoted keys, no trailing commas, no comments. Learn those rules and most parse errors become instantly recognisable rather than mysterious. The comparisons matter less than the defaults — JSON for machine-to-machine data, YAML for files people hand-edit, XML when you need its schema and transformation tooling. And treat minification as a shipping concern and formatting as a reading concern, not competing styles.
Next time a payload fails to parse or an API response is an unreadable wall of text, paste it into the JSON Formatter. It will indent valid JSON immediately and pinpoint the syntax error if there is one — in your browser, with nothing uploaded anywhere.
Frequently asked questions
Is JSON case-sensitive?
Yes. JSON keys and string values are case-sensitive, so "userId" and "userid" are two different keys. The literals true, false, and null must also be lowercase — True or NULL is invalid JSON.
Can JSON have comments?
No. The JSON specification has no comment syntax, and standard parsers reject // and /* */. If you need annotated config files, use JSONC, JSON5, or YAML, and strip comments before parsing with a strict JSON parser.
What's the difference between JSON and a JavaScript object?
JSON is a text format; a JavaScript object is an in-memory data structure. JSON requires double-quoted keys and allows only strings, numbers, booleans, null, arrays, and objects, while JavaScript objects allow unquoted keys, single quotes, functions, undefined, dates, and comments.
Does JSON allow trailing commas?
No. A comma after the last element of an array or the last member of an object is a syntax error in JSON. This is one of the most common causes of "Unexpected token" parse failures.
What data types does JSON support?
JSON supports six types: string, number, boolean, null, array, and object. There is no separate integer, date, or binary type — dates are usually encoded as ISO 8601 strings and binary data as Base64 strings.
What is the difference between a JSON object and a JSON array?
An object is an unordered set of key-value pairs wrapped in curly braces, accessed by key. An array is an ordered list wrapped in square brackets, accessed by numeric index. Use objects for named fields and arrays for collections of similar items.
Should I minify JSON in production?
Minify JSON for anything sent over the network — API responses, config bundles, and logs — because whitespace is pure overhead, and gzip compounds the saving. Keep formatted JSON for files humans edit and read, such as committed configuration.
Is JSON a programming language?
No. JSON is a data interchange format with no logic, variables, or execution model. It only describes structured data, which is why it is safe to parse with JSON.parse rather than evaluating it as code.
Try the related tools
JSON Formatter & Beautifier
Format, indent, validate, and beautify JSON with custom spacing.
JSON Minifier
Minify JSON by stripping whitespace and formatting for production.
JSON Validator & Linter
Validate JSON syntax and view exact error line, column, and diagnostic tips.
JSON Tree Viewer
Visualize JSON hierarchy with collapsible outline tree view.
Related articles
What Is JSON? A Beginner's Explanation
What is JSON? A plain-English explanation of JSON meaning, syntax, and why every API uses it — with a real example and answers to the questions beginners ask.
JSON vs XML: Which Data Format Should You Use?
JSON vs XML compared head-to-head on size, parsing speed, schemas, tooling and API fit — plus the specific cases where XML still beats JSON in 2026.
How to Format and Beautify Minified JSON
How to format JSON: beautify a minified payload in the browser, in your editor, or from the command line — plus indentation choices and when to keep it minified.
Common JSON Syntax Errors and How to Fix Them
Every common JSON syntax error explained: trailing commas, unquoted keys, single quotes, comments and bad escapes — what each message means and how to fix it.