Introduction: JSON Is the Web's Universal Data Language
JSON — JavaScript Object Notation — is the most widely used data interchange format on the internet. It underpins virtually every REST API, powers NoSQL databases like MongoDB and CouchDB, and serves as the configuration format for countless development tools including package.json, tsconfig.json, and docker-compose overrides. If you work with web technology, you work with JSON every day.
Despite its near-ubiquity, JSON's strict syntax trips up developers constantly. A single misplaced comma, an unquoted key, or a JavaScript comment pasted into a JSON file causes a complete parse failure with an error message that varies by runtime. This guide covers JSON from the ground up: its history, data types, syntax rules, the most common errors, and how it compares to alternative formats. Use our free JSON formatter and validator to catch and fix errors instantly as you follow along.
JSON History: From JavaScript Literals to an IETF Standard
Douglas Crockford formalized JSON around 2001, recognizing that JavaScript object literal syntax — already used in browsers — could serve as a lightweight alternative to XML for data exchange. The format was so simple it needed no parser code for JavaScript environments: eval() could parse it directly (though this was later identified as a security risk; see the section on safe parsing below).
JSON gained formal standardization through ECMA-262 (as a JavaScript subset) and later through the IETF. RFC 4627 (2006) was the first dedicated JSON RFC. RFC 7159 (2014) superseded it with important clarifications, notably that a JSON text could be any JSON value — not just an object or array. RFC 8259 (2017) is the current definitive specification, replacing RFC 7159 and aligning with the ECMA-404 standard. When someone refers to "valid JSON," they mean RFC 8259-compliant JSON.
A common source of confusion: JSON was derived from JavaScript object syntax but is not a subset of JavaScript. JSON requires double-quoted strings, forbids trailing commas and comments, and does not support undefined, functions, or Date objects. A valid JavaScript object literal is almost never valid JSON.
JSON Data Types: Six Primitive Values
JSON has exactly six data types. Every value in a JSON document must be one of these:
String
A sequence of Unicode characters wrapped in double quotes: "hello world". Strings must use double quotes — single quotes are a syntax error. Special characters inside strings must be escaped with a backslash: \" (double quote), \\ (backslash), \/ (forward slash, optional), \n (newline), \r (carriage return), \t (tab), \uXXXX (Unicode escape for any code point).
Number
JSON numbers use standard decimal notation: 42, -7, 3.14, 1.5e10. JSON does not support octal (077), hexadecimal (0xFF), NaN, Infinity, or -Infinity. These are JavaScript-specific values absent from the JSON specification. Numbers larger than Number.MAX_SAFE_INTEGER (2^53 − 1) lose precision when parsed by JavaScript; for large integers, use strings.
Boolean
Exactly true or false in lowercase. True, TRUE, or "true" (a string) are not boolean values in JSON.
Null
Exactly null in lowercase. Represents an intentionally absent or empty value.
Object
An unordered collection of key-value pairs wrapped in curly braces. Keys must be strings (double-quoted). Values can be any JSON type. Key-value pairs are separated by commas, keys and values are separated by colons:
{"name": "Alice", "age": 30, "active": true}
JSON objects do not guarantee key ordering. Duplicate keys are technically allowed by the spec but have undefined behavior — most parsers keep the last value while some reject the document entirely. Avoid duplicate keys.
Array
An ordered list of values wrapped in square brackets, separated by commas. Values can be any JSON type and need not be homogeneous:
[1, "two", null, true, {"key": "value"}]
JSON Syntax Rules: The Complete List
JSON's syntax rules are intentionally minimal. Violations cause immediate parse failures:
- Always double-quoted strings. Single quotes (
'value') are a syntax error. - No trailing commas.
{"a": 1,}and[1, 2, 3,]are invalid. The comma after the last element is forbidden. - No comments. Neither
// line commentsnor/* block comments */exist in JSON. This is the most common mistake when copying configuration snippets from documentation that uses JSONC (JSON with Comments). - No undefined. JavaScript's
undefinedhas no equivalent in JSON. Serializing an object withundefinedvalues viaJSON.stringify()silently drops those keys. - No functions. JSON is a data format, not a code format. Functions cannot be represented.
- No
NaNorInfinity. These JavaScript number values have no JSON representation. Attempting to stringify them producesnull. - No hexadecimal numbers.
0xFFis not a valid JSON number. - Keys must be strings.
{name: "Alice"}(unquoted key) is invalid JSON, though valid JavaScript. - Unicode is valid. JSON supports any Unicode character in strings. Non-ASCII characters can appear literally or as
\uXXXXescapes.
Common JSON Syntax Errors and How to Fix Them
The following errors account for the vast majority of JSON parse failures in practice. Our JSON validator catches all of them and highlights the exact line and character position:
Trailing Comma
The most common error. Easy to introduce when adding or removing the last item in an object or array:
// Invalid:
{"name": "Alice", "age": 30,}
// Valid:
{"name": "Alice", "age": 30}
Single-Quoted Strings
Common when developers familiar with Python or JavaScript object syntax write JSON by hand:
// Invalid:
{'name': 'Alice'}
// Valid:
{"name": "Alice"}
Unquoted Keys
Valid in JavaScript but not in JSON:
// Invalid (JavaScript object literal, not JSON):
{name: "Alice"}
// Valid JSON:
{"name": "Alice"}
Comments
Copied from JSONC configuration examples:
// Invalid:
{"port": 3000 // development port
}
Missing Closing Bracket
Especially prevalent in nested structures. The parser error message ("Unexpected end of input") indicates the structure was never closed:
// Invalid:
{"user": {"name": "Alice", "roles": ["admin", "editor"]}
// Missing the outer closing brace
NaN and Infinity
JavaScript-specific values that have no JSON equivalent:
// Invalid JSON (valid JavaScript):
{"ratio": NaN, "limit": Infinity}
// Valid alternatives:
{"ratio": null, "limit": 1e308}
JSON vs Similar Formats
JSON is not the only data format. Choosing the right format for a given use case requires understanding the trade-offs:
JSON vs YAML
YAML is a superset of JSON (any valid JSON is valid YAML) and is designed for human authoring. YAML supports comments, multi-line strings, references/anchors, and does not require quotes for most strings. It uses indentation for structure rather than braces and brackets. YAML is preferred for configuration files (GitHub Actions, Kubernetes, Ansible) because humans edit it frequently. JSON is preferred for machine-to-machine API communication because its strict syntax is faster to parse and less ambiguous.
JSON vs XML
XML was the dominant data interchange format before JSON. XML supports attributes, schemas (XSD), namespaces, and mixed content (text nodes interleaved with element nodes). JSON is significantly more compact for the same data: an XML representation that is 2–3× larger than JSON is common. JSON is easier to work with in JavaScript. XML remains prevalent in enterprise systems (SOAP services, document formats like DOCX/XLSX) and in industries that require its validation ecosystem.
JSON vs TOML
TOML (Tom's Obvious Minimal Language) is designed specifically for configuration. It supports comments, is more readable for deeply nested config, and handles multi-line strings naturally. TOML is not suitable for generic data interchange (no array of objects with heterogeneous types) and is not as universally supported as JSON.
JSON vs Protocol Buffers
Protocol Buffers (protobuf) is a binary serialization format from Google. Protobuf messages are schema-defined, typically 3–10× smaller than JSON, and faster to serialize/deserialize. The trade-off: binary format is not human-readable, requires schema files and code generation, and is harder to debug. Protobuf is preferred for high-throughput internal microservice communication; JSON for public APIs where human readability and language-agnostic parsing matter.
JSON5 and JSONC
JSON5 is a superset of JSON that allows comments, trailing commas, single-quoted strings, and multi-line strings. JSONC (JSON with Comments) adds only comments and trailing commas. Both are used in developer tooling configuration files (tsconfig.json accepts JSONC). Neither JSON5 nor JSONC should be used in API communication — standard JSON parsers will reject them.
JSON in APIs: Conventions and Headers
REST APIs that exchange JSON should use the Content-Type: application/json header on both requests and responses. This tells clients and proxies the body's format. For requests, additionally set Accept: application/json to indicate the expected response format.
During development and debugging, pretty-printed JSON (with indentation and newlines) is significantly easier to read. For production API responses, minified JSON (no unnecessary whitespace) reduces payload size. The difference can be 20–30% of the uncompressed size for typical API responses. Most production APIs apply gzip or brotli compression for all text responses, which largely eliminates the whitespace overhead — but minifying still reduces memory usage during parsing.
Use our JSON formatter to instantly switch between beautified and minified JSON, or to validate an API response during debugging.
Parsing JSON Safely
In JavaScript, the correct way to parse JSON is JSON.parse(jsonString). Never use eval(jsonString) — while it technically works for valid JSON, it executes arbitrary JavaScript code and is a critical security vulnerability if the JSON string comes from an untrusted source.
JSON.parse() throws a SyntaxError if the input is not valid JSON. Always wrap it in a try/catch when handling external data:
try {
const data = JSON.parse(rawString);
// use data
} catch (e) {
console.error("Invalid JSON:", e.message);
}
The reviver parameter to JSON.parse() lets you transform values during parsing. A common use case is converting ISO 8601 date strings back into JavaScript Date objects:
JSON.parse(text, (key, value) => {
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
})
For numbers larger than Number.MAX_SAFE_INTEGER, JavaScript's JSON.parse() loses precision. If your API handles large integers (database IDs beyond 2^53, financial amounts in satoshis), represent them as strings in JSON or use a library like json-bigint for correct BigInt parsing.
JSON Schema: Validating Structure, Not Just Syntax
JSON Schema is a vocabulary for describing the structure of JSON documents. Where JSON syntax validation checks that the text is parseable, JSON Schema validation checks that the parsed data conforms to an expected shape: required fields are present, values have the correct types, strings match patterns, numbers fall within ranges.
A minimal JSON Schema for a user object:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email"],
"properties": {
"id": {"type": "integer", "minimum": 1},
"email": {"type": "string", "format": "email"},
"name": {"type": "string", "maxLength": 100}
},
"additionalProperties": false
}
JSON Schema is valuable for API contracts: the schema describes exactly what the API accepts, client libraries can auto-validate requests and responses, and CI pipelines can enforce schema compatibility on every build using libraries like ajv (Node.js), jsonschema (Python), or Newtonsoft.Json.Schema (.NET).
How Our JSON Formatter Helps You Work With JSON
Our free JSON formatter and validator provides three core functions that address the most common JSON workflow needs:
- Syntax validation: Paste any JSON text and instantly see whether it is valid. Error messages include the line number and character offset for fast diagnosis. Common errors like trailing commas, single quotes, and missing brackets are detected and reported clearly.
- Beautify: Convert minified or single-line JSON into indented, human-readable form. Essential when debugging compressed API responses or reading configuration files that were machine-generated.
- Minify: Strip all whitespace to produce the most compact JSON representation. Useful before embedding JSON in a JavaScript file, storing it in a database column, or sending it as a URL parameter.
All processing happens entirely in your browser — JSON data never leaves your machine. No account is required, and there are no file size limits.