JSON Cheat Sheet

JSON cheat sheet: data types, double-quote and backslash escaping, JSON.parse/stringify, MIME type, big-integer precision and date handling — quick lookup while writing APIs or configs.

How It Works

JSON (JavaScript Object Notation) is a lightweight data-interchange format with only six types: string, number, object, array, boolean and null. It grew from JS literal syntax but is now language-neutral.

Versus XML it is more compact and easier for programs to parse. Mind its strictness: keys and strings must use double quotes, no trailing commas, no comments, and no NaN/Infinity numbers. JSON describes data, never style or behavior.

When to Use This Table

This table is for confirming JSON syntax details. It lists the legal forms, meaning and examples for each type and syntax — string, number, boolean, null, object, array — and covers the easy-to-miss points such as escaping and nesting depth. It is the reference for writing API documentation or diagnosing parse errors.

When not to consult it: you are designing a JSON schema, planning version evolution or comparing against GraphQL. The syntax rules here answer what is legal JSON, never how the data should be structured.

Rule of thumb: mind how JSON differs from JavaScript. JSON is a data format and JavaScript a language, and their literals barely overlap: JSON has no undefined, no comments, no trailing commas, and its top level may be any value whereas a JavaScript object literal may not be a bare number. These differences are the root of cross-language parse failures.

Mind the number and string boundary: JSON permits large integers, yet many parsers read them as floats and lose precision. Conversely a value that should be a number but is written as a string arrives silently as a string with no error raised.

Boundaries and Common Pitfalls

  • Large integers lose precision in most language parsers

    JSON allows numbers of any length, but JavaScript JSON.parse converts integers above 2^53 into doubles and silently truncates the low-order digits. Snowflake IDs, order numbers and amounts in minor units are all affected, and nothing is raised — the data looks fine while the last digits change. Practical options: carry large integers as strings (Snowflake IDs are often strings anyway) or parse with a big-number-capable parser; store them as strings or NUMERIC in the database too.

  • Trailing commas are illegal in strict parsers

    The JSON grammar forbids trailing commas, yet editors and beginners produce [1, 2, 3,] all the time. A permissive JavaScript parser accepts it while a strict Python or Java parser errors out, often pointing at end of line rather than the real character. Worse, the same file then behaves differently across services — passing locally and returning 500 in production. Normalise on write: JSON.stringify never emits trailing commas, and validate before accepting inbound payloads.

  • Comments and single quotes are not JSON

    JSON allows only double-quoted strings and no comments. These two carry-over JavaScript habits are the most common source of invalid payloads. During development JSON5 or commented .jsonc config files are fine, but the wire format must be pure JSON. When an interface genuinely needs explanation, use a schema field such as description or OpenAPI documentation rather than comments inside the payload.

How This Relates to Neighbours

To pretty-print, validate or format JSON, use the in-site JSON formatter; this page is a syntax reference, not a processing tool.

Writing JSON Schema for interface contracts is data modelling, out of scope here.

Choosing between JSON, YAML, TOML and XML is format selection requiring scenario judgement, not lookup.

If the goal is debugging a parse failure you normally need the actual payload and the server-side parser type; the syntax table alone will not localise it.

Practical Snippet

Key points: (1) JSON accepts only double quotes, no comments and no trailing commas — JavaScript habits that make strict parsers fail outright; (2) integers above 2^53 silently lose precision in most parsers, so large values such as snowflake IDs, order numbers and minor currency units should travel as strings; (3) passing locally does not mean passing in production, since permissive and strict parsers disagree; (4) validate inbound payloads before use and strip __proto__ keys against prototype pollution; (5) normalise outbound with JSON.stringify, which never emits trailing commas.

// ① 语法速查:合法 vs 常见错误
const ok = { s: "double only", n: 1e3, b: true, z: null, a: [1, 2] }
const bad = {
  // single: 'not valid JSON',      // ❌ 单引号
  // n1: 0800,                    // ❌ 非法数字(前导 0)
  // t: undefined,                // ❌ undefined 不存在
  // a: [1, 2, 3,],               // ❌ 尾随逗号
}
// console.log(JSON.stringify(bad))   // 注释被丢掉,undefined 被丢掉

// ② 🔴 大整数精度丢失(静默发生,不报错)
const big = '{"id":9007199254740993}'          // 2^53 + 1
const parsed = JSON.parse(big)
console.log(parsed.id)                         // 9007199254740992 ← 末位丢了
console.log(parsed.id === 9007199254740993n)   // false
// ✅ 方案:传字符串
console.log(JSON.parse('{"id":"9007199254740993"}').id)   // '9007199254740993'

// ③ 转义:控制字符与引号必须转义
const risky = { note: 'He said "hi"
and left' }
console.log(JSON.stringify(risky))
// {"note":"He said "hi"
and left"}   ← 正确转义

// ④ 解析前校验:别等运行时才发现格式错误
function parseJsonSafely(text) {
  try {
    const v = JSON.parse(text)
    if (v === null || typeof v !== 'object') {
      return { ok: false, error: '顶层必须是对象或数组' }
    }
    return { ok: true, value: v }
  } catch (e) {
    return { ok: false, error: String(e.message) }
  }
}
console.log(parseJsonSafely('{"a":1}'))        // { ok: true, ... }
console.log(parseJsonSafely('{"a":1,}'))       // { ok: false, ... }

// ⑤ 出站前规范化:stringify 不会产生尾随逗号
console.log(JSON.stringify({ a: 1, b: [1, 2] }, null, 2))

// ⑥ 深度解析与原型污染防护(来自不可信输入时)
const safe = JSON.parse(text, (k, v) => (k === '__proto__' ? undefined : v))

Practical Notes

  • JSON does not guarantee key order, even if most parsers preserve itThe spec defines objects as unordered, so order is not a contract. Yet JSON.parse in JS and json in Python both preserve insertion order, which makes people assume it is guaranteed. Sort explicitly if order matters.
  • Large integers lose precisionJS numbers are doubles, so integers beyond 2^53-1 (snowflake IDs, some timestamps) are rounded after JSON.parse. Send big integers as strings, or use a BigInt-aware parsing path on the client.
  • JSON.parse errors barely tell you where the problem isSyntaxError: Unexpected token } gives no character offset, and line numbers are often normalized away. For large documents, minify first or use a parser that reports positions instead of guessing from the message.

Data Sources

  • RFC 8259 (STD 90)
  • ECMA-404 (The JSON Data Interchange Syntax)

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

Type / SyntaxMeaningExample
stringText value wrapped in double quotes"name": "Tom"
numberInteger or float (no leading zero, no NaN/Infinity)"age": 30
booleanBoolean true or false"active": true
nullEmpty value (must be lowercase)"deleted": null
objectUnordered key-value collection in braces{"id": 1, "name": "Tom"}
arrayOrdered list of values in brackets["a", "b", "c"]
"key"Key must be a double-quoted string"key": value
escape \"Escape a double quote inside strings as \""q": "He said \"hi\""
\\Backslash itself is escaped as \\ (e.g. path C:\\temp)"p": "C:/tmp"
\b \f \n \r \tControl characters use escape sequences"s": "line1\nline2"
\uXXXXUnicode code point as \uXXXX"s": "\u2728"
,Members/elements separated by commas{"a": 1, "b": 2}
no trailing commaNo trailing comma after the last item✗ {"a": 1,}
no commentsStandard JSON has no // or /* */ commentsuse JSONC / JSON5 extensions
root valueTop level may be an object or array[1, 2, 3]
nested objectAn object value may be object/array{"user": {"id": 1}}
nested arrayAn array may hold values of any type[1, "a", {"x": 2}]
duplicate keysLater key wins on parse (avoid duplicates){"a": 1, "a": 2} → 2
JSON.parse()Parse a string to an object; throws on invalidJSON.parse('{"a": 1}')
JSON.stringify()Serialize an object to a stringJSON.stringify(obj, null, 2)
pretty / minifyPretty-print with indent vs minifyJSON.stringify(o, null, 2)
application/jsonUse this MIME type for transportContent-Type: application/json
JSON SchemaDeclarative format to describe data structure{ "$schema": "...", "type": "object" }
big integerIntegers beyond 2^53 lose precision in JS"id": 9007199254740993
datesNo date type; use an ISO 8601 string"ts": "2026-08-29T00:00:00Z"
no leading zeroNo leading zeros on numbers (e.g. 01)"n": 1
JSON vs YAMLYAML allows comments/unquoted/indent; JSON stricter, faster—
JSON vs XMLJSON lighter, nested; XML has tags/attrs/namespaces—

Frequently Asked Questions

What is the difference between JSON and a JavaScript object?

JSON is a pure data format: keys must be double-quoted and values are limited to string/number/boolean/null/object/array — no functions, undefined, Date objects or comments. JS object literals are looser (unquoted keys, methods allowed). JSON.parse/JSON.stringify convert between them.

Why does my JSON fail to parse?

Most common causes: unquoted keys, single-quoted strings, trailing commas, comments, or numbers like 01 / NaN / Infinity. A JSON validator or formatter quickly pinpoints the offending line number.

Why do large integers (e.g. order IDs) get mangled?

JavaScript numbers are double-precision floats; integers beyond 2^53 (9007199254740992) lose precision, so trailing digits distort after parsing. Transmit such IDs as strings, or use BigInt / decimal libraries.

When should I use JSON vs YAML?

Use YAML for human-edited config and Kubernetes manifests (readable, supports comments); use JSON for API transport, logs and NoSQL storage (fast parse, broad ecosystem). They convert to each other.