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

TypeExampleNotes
string"Hello World"Double quotes only. Escape: \" \\ \n \t \r \u0041
number42 or 3.14 or -7 or 1e10Integer or float. No NaN, Infinity, or hex
booleantrue or falseLowercase only. Not True, TRUE, 1, 0
nullnullLowercase 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

json
{
  "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"
}
RuleBad ✗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 caseTrue, False, TRUEtrue, false
Null caseNone, NULL, nilnull
Undefinedundefinednull or omit the key
Number formats0xFF, NaN, InfinityOnly decimal numbers

Common JSON Parse Errors

Error messageCauseFix
Unexpected token , at position NTrailing commaRemove the last comma before } or ]
Unexpected token } at position NTrailing comma or extra }Check closing brackets
Unexpected token ' at position NSingle quotesReplace with double quotes
Unexpected token u at position Nundefined valueReplace with null or omit the key
Unexpected end of JSON inputMissing closing bracketAdd missing } or ]
Expected property nameUnquoted keyWrap key in double quotes

JSON String Escape Sequences

SequenceRepresents
\"Double quote character "
\\Backslash \
\/Forward slash / (optional)
\nNewline (line feed)
\rCarriage return
\tTab
\bBackspace
\fForm feed
\uXXXXUnicode code point (4 hex digits)

JSONPath Quick Reference

json
{
  "store": {
    "books": [
      { "title": "Go Programming", "price": 29.99, "author": "Alan" },
      { "title": "Python Crash",   "price": 19.99, "author": "Eric" }
    ],
    "location": "online"
  }
}
ExpressionSelects
$Root element
$.storeThe store object
$.store.booksThe books array
$.store.books[0]First book object
$.store.books[*]All book objects
$.store.books[*].titleAll book titles
$.store.books[?(@.price < 25)]Books cheaper than 25
$..authorAll 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)

KeywordTypeDescription
$schemametaSchema version URI
typeany"string", "number", "integer", "boolean", "null", "object", "array"
propertiesobjectObject field definitions
requiredobjectArray of required property names
additionalPropertiesobjectfalse = reject unknown properties
itemsarraySchema for array elements
minItems / maxItemsarrayArray length constraints
minimum / maximumnumberValue range constraints
exclusiveMinimumnumberStrict lower bound
minLength / maxLengthstringString length constraints
patternstringRegex the string must match
formatstring"email", "uuid", "date", "date-time", "uri"
enumanyValue must be one of a list
constanyValue must equal exactly this
anyOf / oneOf / allOfanyCombining schemas
$defs / $refanyReusable 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

LanguageParseStringify
JavaScriptJSON.parse(str)JSON.stringify(obj, null, 2)
TypeScriptJSON.parse(str) as TypeJSON.stringify(obj)
Pythonjson.loads(s)json.dumps(obj, indent=2)
Gojson.Unmarshal(data, &v)json.MarshalIndent(v, "", " ")
Javanew ObjectMapper().readValue()objectMapper.writeValueAsString()
Rustserde_json::from_str(&s)serde_json::to_string_pretty(&v)
PHPjson_decode($str, true)json_encode($data, JSON_PRETTY_PRINT)
RubyJSON.parse(str)JSON.pretty_generate(obj)
KotlinJson.decodeFromString<T>(str)Json.encodeToString(obj)
SwiftJSONDecoder().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.

PatternStructure
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 MethodActionReturns
GET /resourcesList collection200 + paginated array
GET /resources/:idFetch one record200 + object or 404
POST /resourcesCreate new record201 + created object
PUT /resources/:idReplace record200 + updated object
PATCH /resources/:idPartial update200 + updated object
DELETE /resources/:idRemove record204 no body

JSON Data Modeling Cheat Sheet

DecisionUse ThisNot 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
IDsStrings with prefix: "usr_9k2m..."Sequential integers (enumerable)
RelationshipsEmbed small/stable, reference largeAlways embed or always reference

JSON Security Quick Reference

RiskPrevention
SQL injection via JSON valueUse parameterized queries — never interpolate JSON into SQL
MongoDB operator injectionSanitize $ prefixed keys (express-mongo-sanitize)
Prototype pollutionUse Object.create(null) or JSON Schema with additionalProperties: false
Sensitive field exposureExplicitly select returned fields — never res.json(fullDbRecord)
ReDoS via JSON validationUse JSON.parse() in try/catch — never a custom regex for JSON
Oversized payload attackSet body size limit: express.json({ limit: '1mb' })
Missing Content-Type checkRequire Content-Type: application/json on mutation endpoints
Insecure deserialization (Java)Disable ObjectMapper.enableDefaultTyping()

Frequently Asked Questions

Yes — JSON keys are case-sensitive. {"Name": "Ravi"} and {"name": "Ravi"} are different keys. The keywords true, false, and null must be lowercase.

The JSON specification does not prohibit duplicate keys, but it says behavior is unpredictable. In practice, most parsers keep the last value seen for a duplicate key. Avoid duplicate keys — some parsers throw errors and others silently overwrite.

JSON numbers have no defined precision limit in the spec. However, JSON.parse() in JavaScript uses IEEE 754 double-precision floats, which lose precision for integers larger than 2^53 (9,007,199,254,740,991). Use strings for large IDs like Snowflake IDs or Twitter IDs.

Use the escape sequence \n inside the string: {"message": "Line 1\nLine 2"}. Actual unescaped newlines inside a string are invalid JSON and will cause a parse error.

JSON arrays are ordered — the index matters. JSON objects are NOT ordered by the specification — parsers may return keys in any order. In practice most parsers preserve insertion order, but never rely on it. If order matters, use an array of objects.

No. JSON is a text format and has no binary type. Encode binary data as Base64 strings before putting them in JSON. Use JSONKit's Base64 tool at /base64 to encode or decode Base64 strings.