JSON Cheatsheet

Syntax, data types, schema & common patterns

Data Format
Contents
📝

Syntax

{
  "name": "Alice",
  "age": 30,
  "active": true,
  "address": null,
  "tags": ["dev", "admin"],
  "profile": {
    "bio": "Hello",
    "avatar": "url"
  }
}

Rules:
• Keys MUST be double-quoted strings
• No trailing commas
• No comments
• No single quotes
📦

Data Types

"string"       String (double quotes only)
42             Number (integer)
3.14           Number (float)
-1             Number (negative)
1.2e10         Number (scientific)
true           Boolean
false          Boolean
null           Null
[1, 2, 3]     Array
{"k": "v"}     Object

No: undefined, NaN, Infinity, Date, RegExp
No: single quotes, hex numbers, octal
🔗

Nested Structures

Array of objects
[
  {"id": 1, "name": "Alice"},
  {"id": 2, "name": "Bob"}
]

Nested objects
{
  "user": {
    "name": "Alice",
    "address": {
      "city": "NYC",
      "zip": "10001"
    }
  }
}

Mixed
{
  "matrix": [[1,2],[3,4]],
  "config": {"debug": false}
}
📐

JSON Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age":  { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" },
    "role": { "enum": ["admin", "user"] }
  },
  "required": ["name", "email"]
}

Parsing

JavaScript
const obj = JSON.parse(jsonStr);
const str = JSON.stringify(obj, null, 2);

Python
import json
obj = json.loads(json_str)
s = json.dumps(obj, indent=2)

CLI (jq)
cat data.json | jq '.'               # pretty print
cat data.json | jq '.name'           # get field
cat data.json | jq '.[0]'            # first element
cat data.json | jq '.[] | .name'     # map
cat data.json | jq 'length'          # count
📋

Common Patterns

API Response
{
  "status": "success",
  "data": { "id": 1, "name": "Alice" },
  "meta": { "page": 1, "total": 50 }
}

Error Response
{
  "error": {
    "code": 404,
    "message": "Not found"
  }
}

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": { "start": "node index.js" }
}
⚠️

Rules & Gotchas

✅ Valid
{"key": "value"}
{"num": 42}

❌ Invalid
{'key': 'value'}       single quotes
{key: "value"}          unquoted key
{"a": 1,}               trailing comma
// comment              no comments
{"a": undefined}        no undefined
{"a": NaN}              no NaN

Use JSONC or JSON5 for comments
MIME type: application/json
File extension: .json