JSON Cheat Sheet
JSON Quick Reference
JSON (JavaScript Object Notation) is a lightweight text format for exchanging structured data. It is human-readable, language-independent, and supported natively by virtually every programming language. This cheat sheet covers everything you need: data types, syntax rules, common errors, JSONPath expressions, and JSON Schema keywords.
JSON supports exactly six value types: string, number, boolean, null, object, and array. Keys must always be strings wrapped in double quotes. Trailing commas are not allowed. Comments are not part of the JSON specification (use JSONC or JSON5 for that).
JSON Data Types
| Type | Example | Notes |
|---|---|---|
| string | "Hello World" | Double quotes only. Escape: \" \\ \n \t \r \u0041 |
| number | 42 or 3.14 or -7 or 1e10 | Integer or float. No NaN, Infinity, or hex |
| boolean | true or false | Lowercase only. Not True, TRUE, 1, 0 |
| null | null | Lowercase only. Not None, nil, NULL |
| object | {"key": value} | Unordered. Keys must be strings. No trailing comma |
| array | [1, "two", true, null] | Ordered. Mixed types allowed. No trailing comma |
JSON Syntax Rules
{
"validString": "double quotes required",
"validNumber": 42,
"validFloat": 3.14,
"validBool": true,
"validNull": null,
"validArray": [1, 2, 3],
"validObject": { "nested": "ok" },
"lastKey": "no trailing comma here"
}| Rule | Bad ✗ | Good ✓ |
|---|---|---|
| String quotes | {'key': 'value'} | {"key": "value"} |
| Trailing comma | {"a": 1,} | {"a": 1} |
| Unquoted key | {name: "Ravi"} | {"name": "Ravi"} |
| Comments | // not allowed | (use JSONC or JSON5) |
| Boolean case | True, False, TRUE | true, false |
| Null case | None, NULL, nil | null |
| Undefined | undefined | null or omit the key |
| Number formats | 0xFF, NaN, Infinity | Only decimal numbers |
Common JSON Parse Errors
| Error message | Cause | Fix |
|---|---|---|
| Unexpected token , at position N | Trailing comma | Remove the last comma before } or ] |
| Unexpected token } at position N | Trailing comma or extra } | Check closing brackets |
| Unexpected token ' at position N | Single quotes | Replace with double quotes |
| Unexpected token u at position N | undefined value | Replace with null or omit the key |
| Unexpected end of JSON input | Missing closing bracket | Add missing } or ] |
| Expected property name | Unquoted key | Wrap key in double quotes |
JSON String Escape Sequences
| Sequence | Represents |
|---|---|
| \" | Double quote character " |
| \\ | Backslash \ |
| \/ | Forward slash / (optional) |
| \n | Newline (line feed) |
| \r | Carriage return |
| \t | Tab |
| \b | Backspace |
| \f | Form feed |
| \uXXXX | Unicode code point (4 hex digits) |
JSONPath Quick Reference
{
"store": {
"books": [
{ "title": "Go Programming", "price": 29.99, "author": "Alan" },
{ "title": "Python Crash", "price": 19.99, "author": "Eric" }
],
"location": "online"
}
}| Expression | Selects |
|---|---|
| $ | Root element |
| $.store | The store object |
| $.store.books | The books array |
| $.store.books[0] | First book object |
| $.store.books[*] | All book objects |
| $.store.books[*].title | All book titles |
| $.store.books[?(@.price < 25)] | Books cheaper than 25 |
| $..author | All authors (recursive) |
| $.store.books[-1:] | Last book |
| $.store.books[0:2] | First two books |
Test JSONPath expressions with the JSONPath Tester.
JSON Schema Keywords (Draft 2020-12)
| Keyword | Type | Description |
|---|---|---|
| $schema | meta | Schema version URI |
| type | any | "string", "number", "integer", "boolean", "null", "object", "array" |
| properties | object | Object field definitions |
| required | object | Array of required property names |
| additionalProperties | object | false = reject unknown properties |
| items | array | Schema for array elements |
| minItems / maxItems | array | Array length constraints |
| minimum / maximum | number | Value range constraints |
| exclusiveMinimum | number | Strict lower bound |
| minLength / maxLength | string | String length constraints |
| pattern | string | Regex the string must match |
| format | string | "email", "uuid", "date", "date-time", "uri" |
| enum | any | Value must be one of a list |
| const | any | Value must equal exactly this |
| anyOf / oneOf / allOf | any | Combining schemas |
| $defs / $ref | any | Reusable schema definitions |
Generate a schema from JSON using the JSON Schema Generator. Validate a document against a schema with the JSON Schema Validator.
JSON in Every Language
| Language | Parse | Stringify |
|---|---|---|
| JavaScript | JSON.parse(str) | JSON.stringify(obj, null, 2) |
| TypeScript | JSON.parse(str) as Type | JSON.stringify(obj) |
| Python | json.loads(s) | json.dumps(obj, indent=2) |
| Go | json.Unmarshal(data, &v) | json.MarshalIndent(v, "", " ") |
| Java | new ObjectMapper().readValue() | objectMapper.writeValueAsString() |
| Rust | serde_json::from_str(&s) | serde_json::to_string_pretty(&v) |
| PHP | json_decode($str, true) | json_encode($data, JSON_PRETTY_PRINT) |
| Ruby | JSON.parse(str) | JSON.pretty_generate(obj) |
| Kotlin | Json.decodeFromString<T>(str) | Json.encodeToString(obj) |
| Swift | JSONDecoder().decode(T.self, from: data) | JSONEncoder().encode(obj) |
| C# | JsonSerializer.Deserialize<T>(str) | JsonSerializer.Serialize(obj) |
JSON REST API Design Patterns
Standard patterns for consistent JSON API responses across all endpoints.
| Pattern | Structure |
|---|---|
| Success envelope | {"success": true, "data": {...}, "meta": {"requestId": "..."}} |
| Error envelope | {"success": false, "error": {"code": "VALIDATION_ERROR", "message": "..."}} |
| Paginated list | {"data": [...], "pagination": {"page": 1, "limit": 20, "total": 847}} |
| Created (201) | {"success": true, "data": {"id": "new_id", ...}} |
| No content (204) | Empty body — do not return a JSON envelope for 204 responses |
| RFC 7807 error | {"type": "...", "title": "Validation Error", "status": 422, "detail": "..."} |
| HTTP Method | Action | Returns |
|---|---|---|
| GET /resources | List collection | 200 + paginated array |
| GET /resources/:id | Fetch one record | 200 + object or 404 |
| POST /resources | Create new record | 201 + created object |
| PUT /resources/:id | Replace record | 200 + updated object |
| PATCH /resources/:id | Partial update | 200 + updated object |
| DELETE /resources/:id | Remove record | 204 no body |
JSON Data Modeling Cheat Sheet
| Decision | Use This | Not This |
|---|---|---|
| Collections | [{"id":1,...},{"id":2,...}] | {"1":{...},"2":{...}} |
| Optional absent | {"middleName": null} | Omit the key |
| Dates | "2025-06-01T12:00:00Z" (ISO 8601) | 1748779200 (epoch) or "01/06/2025" |
| Money | {"amount":1299,"currency":"INR"} | {"amount":12.99} |
| Boolean flags | "isActive": true | "active": 1 or "active": "yes" |
| Enumerations | "status": "active" | "status": 2 |
| IDs | Strings with prefix: "usr_9k2m..." | Sequential integers (enumerable) |
| Relationships | Embed small/stable, reference large | Always embed or always reference |
JSON Security Quick Reference
| Risk | Prevention |
|---|---|
| SQL injection via JSON value | Use parameterized queries — never interpolate JSON into SQL |
| MongoDB operator injection | Sanitize $ prefixed keys (express-mongo-sanitize) |
| Prototype pollution | Use Object.create(null) or JSON Schema with additionalProperties: false |
| Sensitive field exposure | Explicitly select returned fields — never res.json(fullDbRecord) |
| ReDoS via JSON validation | Use JSON.parse() in try/catch — never a custom regex for JSON |
| Oversized payload attack | Set body size limit: express.json({ limit: '1mb' }) |
| Missing Content-Type check | Require Content-Type: application/json on mutation endpoints |
| Insecure deserialization (Java) | Disable ObjectMapper.enableDefaultTyping() |