53 entries · 6 sections
JSON Cheat Sheet
JSON's complete data model — it really is only six kinds of value — plus the syntax rules that cause most parse errors, the parse and serialise APIs in JavaScript and Python, everyday jq filters, and the JSON Schema keywords worth knowing.
The six value types
| Syntax | What it does |
|---|---|
"text" | String. Double quotes only — single quotes are not JSON. |
42, -3, 2.5, 1e3 | Number. There is one numeric type, and no NaN, no Infinity and no leading plus sign. |
true / false | Booleans, always lower-case. |
null | The null value. There is no undefined in JSON. |
{ "key": value } | Object: an unordered collection of string-keyed members. |
[1, 2, 3] | Array: an ordered list whose values may be of different types. |
Syntax rules that cause parse errors
| Syntax | What it does |
|---|---|
{"a": 1,} | A trailing comma is invalid. This is the single most common JSON error. |
{'a': 1} | Single quotes are invalid; both keys and string values need double quotes. |
{a: 1} | Unquoted keys are JavaScript object literal syntax, not JSON. |
// comment | Comments are not part of JSON. JSONC and JSON5 add them; a plain parser rejects them. |
A literal newline inside a string | Invalid. Escape it as \n. |
\" \\ \/ \b \f \n \r \t \uXXXX | The complete list of escape sequences JSON strings allow. |
0123 | Leading zeros are invalid, as is a bare .5 or a trailing 5. — write 0.5 and 5.0. |
A byte-order mark | JSON text is Unicode, normally UTF-8, and a BOM makes many parsers fail on the first byte. |
Duplicate keys | Not forbidden by the specification, but the result is undefined. Most parsers keep the last one. |
JavaScript
| Syntax | What it does |
|---|---|
JSON.parse(text) | Parse a string into a value. Throws SyntaxError on bad input, so wrap it in try/catch. |
JSON.parse(text, reviver) | Transform each value as it is parsed — how you turn ISO strings back into Dates. |
JSON.stringify(value) | Serialise to a compact string. |
JSON.stringify(value, null, 2) | Pretty-print with a two-space indent. |
JSON.stringify(value, ["a", "b"]) | Include only the listed keys. |
JSON.stringify(value, replacer) | Transform values on the way out, or drop them by returning undefined. |
toJSON() on your object | A method that decides the object's own serialised form. Date implements it, which is why dates become ISO strings. |
await res.json() | Parse a fetch response body. |
Dropped values | undefined, functions and symbols vanish from objects and become null inside arrays. |
structuredClone(obj) | Deep-copy without a JSON round trip, keeping Dates, Maps, Sets and cyclic references. |
Python
| Syntax | What it does |
|---|---|
json.loads(text) | Parse a JSON string. |
json.load(fp) | Parse from an open file object. |
json.dumps(obj) | Serialise to a string. |
json.dumps(obj, indent=2) | Pretty-print. |
json.dumps(obj, sort_keys=True) | Stable key order, which makes generated files diff cleanly. |
json.dumps(obj, ensure_ascii=False) | Keep non-ASCII characters readable instead of escaping them as \uXXXX. |
json.dumps(obj, default=str) | Fall back to str() for types JSON does not know, such as datetime and Decimal. |
json.dump(obj, fp) | Write directly to a file object. |
json.JSONDecodeError | The exception to catch. It carries .msg, .lineno, .colno and .pos. |
jq on the command line
| Syntax | What it does |
|---|---|
jq . file.json | Pretty-print and validate in one step. |
jq -r '.name' file.json | Read one field as raw text, without the surrounding quotes. |
jq '.items[]' file.json | Emit each element of an array as a separate document. |
jq '.items[] | .id' file.json | Pipe each element into another filter. |
jq '.items | length' | Count the elements. |
jq 'map(.price) | add' | Sum one field across an array. |
jq '.[] | select(.active)' | Keep only the elements matching a condition. |
jq -c '.' | Compact output, one document per line. |
jq -s '.' | Slurp several JSON documents into a single array. |
curl -s <url> | jq '.data' | The everyday use: inspect part of an API response. |
Related formats and JSON Schema
| Syntax | What it does |
|---|---|
.jsonl / NDJSON | One JSON document per line. Streamable and appendable — and not itself a valid JSON document. |
JSON5 / JSONC | Relaxed dialects with comments and trailing commas. tsconfig.json and VS Code settings use JSONC. |
"$schema" | Points a document at the JSON Schema that describes it, which is what gives editors autocomplete. |
"type": "object" | The JSON Schema keyword that constrains a value's type. |
"required": ["id"] | Which properties must be present. |
"properties": { ... } | A schema for each named property. |
"additionalProperties": false | Reject any property not declared. Off by default, which surprises people. |
"enum": ["a", "b"] | Restrict a value to a fixed set. |
JSON-LD | JSON plus an @context, used for the structured data search engines read. |
Worth knowing
- JSON has no date type. Every timestamp you see is a string by convention, almost always ISO 8601 in UTC. JSON.stringify turns a Date into that string automatically, but JSON.parse will not turn it back — you need a reviver function, or a schema-aware parser, on the way in.
- JSON numbers have no precision limit in the specification, but JavaScript parses them into doubles. Any integer above 2^53-1 — a Twitter/X id, a Postgres bigint, a nanosecond timestamp — silently loses precision through JSON.parse. Send those as strings.
- When a parse fails, look for a trailing comma first, then for single quotes, then for an unescaped newline or control character inside a string. Piping the file through jq . gives you the line and column of the first problem, which is faster than reading it.
Try a snippet instead of reading about it
Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.
Open the editorJSON — common questions
- Can JSON have comments?
- No. The specification has no comment syntax, and a conformant parser will reject them. The workarounds are to use a dialect that adds them — JSONC, which VS Code settings and tsconfig.json use, or JSON5 — or to add a normal string field such as "_comment" that the consumer ignores.
- What is the difference between JSON and a JavaScript object?
- JSON is a text format; a JavaScript object is a runtime value. JSON requires double-quoted keys and strings, forbids trailing commas, comments, functions and undefined, and allows only six value types. Almost all JSON is valid JavaScript, but the reverse is very far from true.
- Why do my large numbers change when I parse JSON?
- JavaScript parses every JSON number into a 64-bit float, which represents integers exactly only up to 2^53-1 — about 9.007 quadrillion. Larger ids get rounded silently. The fix is to transmit them as strings, or to use a parser that produces BigInt values.
- What is NDJSON and when should I use it?
- Newline-delimited JSON puts one complete JSON document on each line, so a consumer can process records as they arrive without buffering the whole file, and a producer can append without rewriting anything. It is the right format for logs, exports and streaming APIs. Note that the file as a whole is not valid JSON — parse it line by line.