JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging structured data, built from objects of key/value pairs, ordered arrays, and a handful of value types: strings, numbers, true, false and null. It is the default format for web APIs and many configuration files because it is easy for people to read and simple for every programming language to parse. JSON is strict: keys and strings need double quotes, and trailing commas and comments are not allowed.
- JSON has exactly six kinds of value: object, array, string, number, boolean (
true/false) andnull. - Keys must be strings in double quotes; single quotes are never valid.
- No trailing commas, no comments, no
undefined,NaNorInfinity. - Most "invalid JSON" errors come from a missing or extra comma, a wrong quote, or an unescaped character in a string.
- Validate syntax with a strict parser first, then validate structure with JSON Schema if you need to.
What JSON looks like
JSON grew out of the syntax JavaScript uses for object literals, but it is language-independent. It is defined in RFC 8259 and in the ECMA-404 standard, and the one-page summary at json.org describes the whole grammar. A typical document looks like this:
{
"id": 1042,
"name": "Ada Lovelace",
"email": "ada@example.com",
"active": true,
"score": 98.5,
"manager": null,
"roles": ["admin", "editor"],
"address": {
"city": "London",
"postcode": "N1 9GU"
}
}
Whitespace between elements (spaces, tabs and line breaks) is ignored, so the same data can be written on one line or spread out with indentation. The top level of a JSON document can be any value, although APIs almost always use an object or an array.
JSON data types
| Type | Example | Rules |
|---|---|---|
| Object | {"a": 1, "b": 2} | Unordered set of key/value pairs in curly braces. Keys are strings; a colon separates key and value; commas separate pairs. |
| Array | [1, "two", false] | Ordered list of values in square brackets, separated by commas. Values can be of mixed types. |
| String | "caf\u00e9 \"quoted\"" | Double quotes only. Backslash escapes: \" \\ \/ \b \f \n \r \t and \uXXXX. Raw line breaks and tabs inside strings are not allowed. |
| Number | -12, 3.14, 6.02e23 | Decimal only. No leading +, no leading zeros (07), no hexadecimal, no NaN or Infinity. A decimal point must have digits on both sides. |
| Boolean | true, false | Lower case, without quotes. |
| Null | null | Lower case, without quotes. Represents an empty or unknown value. |
There is no date type. Dates are usually written as strings in ISO 8601 format, such as "2026-10-13T09:30:00Z", or as Unix timestamps in numbers; our timestamp converter translates between the two.
Numbers and precision
The JSON standard does not limit the size or precision of numbers, but the programs reading it do. JavaScript stores numbers as 64-bit floating point values, so integers larger than 9,007,199,254,740,991 (253 − 1) can silently lose precision. For large IDs, many APIs send them as strings, for example "id": "1234567890123456789".
The rules that trip people up
JSON looks like JavaScript, Python dictionaries and YAML, which is exactly why people write invalid JSON by accident. These rules have no exceptions in standard JSON:
- Keys must be strings in double quotes.
{name: "Ada"}is valid JavaScript but invalid JSON; write{"name": "Ada"}. - Only double quotes.
'Ada'is not a JSON string. - No trailing commas.
[1, 2, 3,]and{"a": 1,}are invalid. - No comments. Neither
// ...nor/* ... */is allowed. - Literal values are lower case.
True,FALSEandNone(Python's spelling) are invalid; usetrue,falseandnull. - No
undefined, functions or special numbers. These exist in JavaScript but have no JSON equivalent. - Keys should be unique. The standard says names within an object should be unique; with duplicates, parsers behave differently, and many silently keep only the last one.
Some tools accept relaxed variants. Files such as VS Code's settings.json and TypeScript's tsconfig.json are read with parsers that allow comments (often called JSONC), and JSON5 allows comments, single quotes and trailing commas. These are separate formats: a standard JSON parser, including the one your API client or server uses, will reject them.
Common JSON errors and how to fix them
Error wording differs between parsers. The table shows the kind of message you will see from Python's json module or a browser's JSON.parse, what it usually means, and the fix. The reported position often points just after the real mistake, so look at the character before it as well.
| Problem | Typical error message | Fix |
|---|---|---|
Trailing comma: {"a": 1,} | "Expecting property name enclosed in double quotes" or "Unexpected token }" | Delete the comma after the last item in the object or array. |
Unquoted or single-quoted key: {a: 1}, {'a': 1} | "Expecting property name enclosed in double quotes" or "Expected double-quoted property name" | Wrap every key in double quotes. |
Single-quoted string value: {"a": 'x'} | "Expecting value" or "Unexpected token '" | Use double quotes, and escape any double quotes inside as \". |
| Missing comma between items | "Expecting ',' delimiter" or "Expected ',' or '}' after property value" | Add a comma between the two values or pairs at the reported line. |
| Comment in the file | "Expecting value" or "Unexpected token /" | Remove the comment, or move the note into a data field such as "_comment". |
Python or JavaScript literals: True, None, undefined, NaN | "Expecting value" or "Unexpected token" | Use true, false or null; serialise data with a real JSON library rather than printing it. |
| Raw line break or tab inside a string | "Invalid control character" or "Bad control character in string literal" | Replace it with \n or \t. |
Unescaped backslash, such as a Windows path "C:\new" | "Invalid \escape" or "Bad escaped character" | Double the backslashes: "C:\\new". |
| Missing closing bracket or quote | "Unterminated string" or "Unexpected end of JSON input" | Check that every {, [ and " is closed; a formatter's indentation makes the gap obvious. |
| Two documents back to back, or text after the end | "Extra data" or "Unexpected non-whitespace character after JSON" | Wrap multiple objects in an array, or process the input as JSON Lines (one document per line). |
| Empty response or HTML error page parsed as JSON | "Expecting value: line 1 column 1" or "Unexpected token <" | Check the HTTP status and response body; the server returned something other than JSON. |
The last row is one of the most frequent in practice: code calls JSON.parse or response.json() on an error page that begins with <!DOCTYPE html>, and the < is reported as an unexpected token.
JSON vs YAML vs XML
| JSON | YAML | XML | |
|---|---|---|---|
| Structure | Braces and brackets | Indentation | Opening and closing tags |
| Comments | No | Yes (#) | Yes (<!-- -->) |
| Data types | String, number, boolean, null, object, array | Similar, plus dates and other types depending on the parser | Everything is text unless a schema assigns types |
| Attributes and mixed content | No | No | Yes |
| Verbosity | Compact | Most compact to read | Most verbose |
| Typical uses | Web APIs, browser storage, package manifests, logs | Configuration: Kubernetes, Docker Compose, CI pipelines | Documents, SOAP, RSS and Atom, sitemaps, office file formats |
| Main pitfalls | Strict quoting and commas | Whitespace-sensitive; some unquoted values are interpreted unexpectedly | Verbose; namespaces and entities add complexity |
YAML 1.2 was designed so that JSON documents are, with rare edge cases, also valid YAML, which makes converting between them straightforward. Our JSON to YAML converter handles both directions, the YAML formatter and XML formatter validate the other two formats, and the CSV to JSON converter turns spreadsheet exports into arrays of objects.
Pretty-printing and minifying
Because whitespace is insignificant, the same JSON can be formatted for humans or for machines:
- Pretty-printed JSON adds line breaks and indentation, usually two or four spaces, so nesting is visible. Use it for configuration files, documentation and debugging.
- Minified JSON removes all optional whitespace to make the payload smaller. Use it for data sent over the network or stored in bulk; HTTP compression also reduces size, so the saving is often modest.
{"name":"Ada","roles":["admin","editor"],"active":true}
Most languages can do both. In JavaScript, JSON.stringify(data, null, 2) pretty-prints with two-space indentation and JSON.stringify(data) minifies. In Python, json.dumps(data, indent=2) pretty-prints and json.dumps(data, separators=(",", ":")) gives the most compact output.
How to validate JSON
Validating JSON has two levels: is it syntactically valid JSON at all, and does it have the structure your application expects?
- Check the syntax with a strict parser. Paste the text into our JSON formatter and validator, which reports the line and column of the first error and runs in your browser. On the command line,
python3 -m json.tool data.jsonorjq . data.jsonprints the formatted document or an error. - Fix errors one at a time. A parser stops at the first problem, so re-run it after each fix until it succeeds.
- Check the structure. Confirm that required fields exist and have the right types, either in code or with a JSON Schema validator.
- Check the encoding. JSON exchanged between systems should be UTF-8. A file saved in another encoding can produce strange characters or errors on non-English text.
JSON Schema in brief
JSON Schema is a vocabulary, written in JSON itself, for describing what a valid document looks like: which properties are required, what type each must be, allowed values, string patterns, numeric ranges and so on. Validators exist for most languages, and API description formats such as OpenAPI use JSON Schema to describe request and response bodies. The specification is published at json-schema.org. A small example:
{
"$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" },
"roles": { "type": "array", "items": { "type": "string" } }
}
}
A document with a missing email or a string id would be valid JSON but fail this schema. Note that many validators treat format as an annotation and do not enforce it unless configured to.
Frequently asked questions
Can JSON have comments?
No. Standard JSON does not allow comments of any kind. Some tools accept JSONC or JSON5, which do, but files meant to be read by other programs should stick to plain JSON. If you need a note, add a field such as "_comment".
Why does JSON not allow trailing commas?
The grammar was kept deliberately minimal and simply does not include them. Many JavaScript engines and other languages accept trailing commas in their own syntax, which is why they often appear in hand-written JSON by mistake.
What is the difference between JSON and a JavaScript object?
JSON is a text format; a JavaScript object is a data structure in memory. JSON's syntax is a stricter subset of JavaScript literal syntax. You convert between them with JSON.parse and JSON.stringify.
What does "Unexpected token < in JSON at position 0" mean?
The text being parsed starts with <, which almost always means you received HTML, such as an error or login page, instead of JSON. Check the request URL, the HTTP status code and the raw response body.
Is the order of keys in a JSON object preserved?
The standard treats objects as unordered, so you should not rely on key order. In practice most modern parsers keep the order they read, but array order is the only order JSON guarantees.
What file extension and MIME type does JSON use?
Files use the .json extension and the media type is application/json, as registered in RFC 8259.