Getting Started
Basic Structure
JSON supports 6 data types: string, number, boolean, null, array, and object. Keys must be strings in double quotes. JSON is language-independent and easy for humans and machines to read.
{
"name": "Alice",
"age": 30,
"isStudent": false,
"height": 1.65,
"nullValue": null,
"hobbies": ["reading", "coding", "music"],
"address": {
"city": "NYC",
"zip": "10001"
}
}JSON Syntax Rules
JSON has strict syntax: keys and strings use double quotes only, commas separate elements, and trailing commas are forbidden. The entire document must be a single JSON value. Standard JSON has no comments—use a preprocessor or JSON5 if you need them.
{
"key": "value", // key MUST be a double-quoted string
"nested": { "a": 1 }, // objects use { } with comma-separated pairs
"list": [1, 2, 3] // arrays use [ ] with comma-separated values
}
// Rules:
// - Double quotes only for strings and keys (no single quotes)
// - Comma separates members; NO trailing comma
// - The whole document is ONE value (usually an object or array)
// - No comments allowed in standard JSONComments in JSON
Standard JSON forbids comments. Common workarounds: add a '_comment' field (ignored by code), use JSONC/JSON5 (supported by VS Code, many tools), or strip comments before parsing with a library like comment-json or JSON.minify.
// Standard JSON does NOT allow comments.
// Workaround 1: include a descriptive field
{
"_comment": "This is a config file for the app",
"port": 8080
}
// Workaround 2: use JSON5 or JSONC (VS Code settings)
{
// line comment
"port": 8080 /* block comment */
}
// Workaround 3: strip comments before parsing
// (e.g., JSON.minify, comment-json npm package)Whitespace & Formatting
Whitespace outside strings is insignificant—compact and pretty forms parse to the same value. Compact JSON saves bandwidth; pretty-printed (2-space indent is common) aids readability and diffs. Most serializers offer a 'pretty' option.
// These are all equivalent:
{"a":1,"b":2} // compact (no whitespace)
{ "a": 1, "b": 2 } // readable
{
"a": 1,
"b": 2
} // pretty-printed
// Whitespace between tokens is insignificant.
// Use compact for transmission, pretty for humans.File Extension & MIME Type
The standard file extension is .json and the MIME type is application/json. Variants like JSONC, JSON5, GeoJSON, and NDJSON have their own conventions. Always use UTF-8 encoding; the BOM is discouraged.
// File extensions:
// .json standard JSON
// .jsonc JSON with comments (VS Code, TypeScript config)
// .json5 JSON5 (relaxed syntax)
// .geojson GeoJSON (geographic data)
// .ndjson Newline-Delimited JSON (JSON Lines)
// .har HTTP Archive (JSON-based)
// MIME type:
Content-Type: application/json
// Older/alternate MIME types (avoid):
// text/json (non-standard)
// application/x-json (non-standard)
// UTF-8 is the default and recommended encoding.JSON Value Categories
JSON values fall into six types: string, number, boolean, null, array, object. Arrays and objects are structured (can hold other values); the rest are primitives. A valid JSON document is one value—commonly an object or array, but a bare number or string is also valid.
// A JSON value is exactly one of these six types:
"hello" // string
42 // number
3.14 // number
true // boolean
false // boolean
null // null
[1, 2, 3] // array
{ "a": 1 } // object
// Structured types: array, object
// Primitive types: string, number, boolean, null
// A standalone JSON document is a single value of any type.Data Types
String Type
JSON strings are double-quoted Unicode text. Common escapes: \" (quote), \\ (backslash), \/ (slash), \n, \t, \r, \b, \f, and \uXXXX for any Unicode code point. Single quotes are not allowed as string delimiters.
{
"single": "double quotes only",
"empty": "",
"escaped": "He said \"hi\" and C:\\Users",
"unicode": "Cafu00e9 \u00e9 \u1F600",
"multiline": "line1\nline2\ttabbed"
}
// Strings MUST use double quotes.
// Single quotes are NOT valid in JSON.Number Type
JSON numbers follow a subset of IEEE 754 double-precision: integers, decimals, and scientific notation (e.g., 6.022e23). Leading zeros are forbidden (007 is invalid). NaN, Infinity, and -Infinity are NOT valid—encode them as null or strings if needed.
{
"integer": 42,
"negative": -7,
"float": 3.14,
"zero": 0,
"scientific": 6.022e23,
"small": 1.5e-10
}
// Numbers are NOT quoted.
// No leading zeros (007 is invalid).
// No NaN, Infinity, or -Infinity (not valid JSON).Boolean Type
JSON booleans are the literal keywords true and false (lowercase, unquoted). Quoted 'true'/'false' are strings. JSON has no concept of 0/1 or yes/no as booleans—convert them in your application code.
{
"enabled": true,
"disabled": false,
"flag": true
}
// Booleans are the bare keywords true and false.
// They are NOT quoted ("true" is a string).
// 0/1, yes/no, on/off are NOT booleans in JSON.Null Type
JSON null is the bare keyword null (unquoted). It signals the intentional absence of a value. Note that null is distinct from an empty string '', 0, false, or a missing key. Many languages map null to None/nil/null.
{
"middleName": null,
"deletedAt": null,
"optional": null
}
// null is a bare keyword (unquoted).
// "null" (quoted) is a string, not null.
// null represents the intentional absence of value.Array Type
JSON arrays are ordered lists wrapped in [ ], comma-separated, zero-indexed. They can hold any JSON value, including mixed types and nested arrays/objects. Empty arrays [] are valid. Order is preserved and significant.
{
"numbers": [1, 2, 3],
"mixed": [1, "two", true, null],
"nested": [[1, 2], [3, 4]],
"objects": [
{ "id": 1 },
{ "id": 2 }
],
"empty": []
}
// Arrays are ordered, zero-indexed, and can hold mixed types.Object Type
JSON objects are unordered key/value collections wrapped in { }. Keys must be unique double-quoted strings; values can be any JSON type. Although objects are conceptually unordered, most parsers preserve insertion order; do not rely on order for correctness.
{
"user": {
"id": 1,
"name": "Alice",
"roles": ["admin", "user"],
"active": true
},
"empty": {}
}
// Objects are unordered collections of key/value pairs.
// Keys MUST be unique strings (double-quoted).
// Values can be any JSON type.Strings
String Basics
JSON strings are double-quoted sequences of Unicode characters. The forward slash can be escaped (\/) but does not need to be—useful when embedding JSON in <script> tags. Empty strings are valid.
{
"name": "Alice",
"email": "[email protected]",
"url": "https://example.com/path?q=1",
"path": "C:\\Users\\alice",
"empty": ""
}
// Strings are double-quoted Unicode text.
// Forward slash may be escaped as \/ but does not have to be.Escape Sequences
JSON supports these escapes: \" (quote), \\ (backslash), \/ (slash), \b (backspace), \f (form feed), \n (newline), \r (carriage return), \t (tab), and \uXXXX (Unicode code point). Any other backslash sequence is invalid.
{
"quote": "She said \"hello\"",
"backslash": "C:\\Users\\name",
"newline": "line1\nline2",
"tab": "col1\tcol2",
"carriage": "a\rb",
"backspace": "a\bb",
"formfeed": "a\fb",
"slash": "a\/b"
}
// Valid escapes: \" \\ \/ \b \f \n \r \t \uXXXXUnicode Characters
Use \uXXXX for any Unicode code point. Characters above U+FFFF (like many emojis) require a surrogate pair: two \u escapes. Modern parsers also accept the raw UTF-8 character directly in the string—\uXXXX is mainly for safety or when you cannot type the character.
{
"eacute": "Caf\u00e9",
"euro": "Price: \u20ac10",
"emoji": "Smile \ud83d\ude00",
"chinese": "\u4f60\u597d",
"raw": "Cafu00e9 u00e9 \u00e9"
}
// \uXXXX encodes a code point in the Basic Multilingual Plane.
// Surrogate pairs (two \u escapes) encode characters above U+FFFF.
// Modern parsers also accept the raw UTF-8 character directly.Special Characters in Strings
Inside JSON strings, the double quote and backslash must always be escaped (\" and \\). Other special characters (HTML, SQL, regex) follow their own rules but JSON only requires escaping \" and \\ (plus control characters). A literal backslash is written as \\.
{
"html": "<div class=\"x\">Hi</div>",
"sql": "SELECT * FROM t WHERE name='O''Brien'",
"regex": "^\\d{3}-\\d{4}$",
"json": "{ \"k\": \"v\" }",
"cmd": "echo \"hello\""
}
// Backslash is the universal escape character.
// To include a literal backslash, write \\.Multi-line Strings (Workaround)
JSON strings cannot contain literal newlines—you must escape them as \n. For multi-line content, either embed \n in the string, use an array of line strings, or switch to a format like YAML or JSON5 that supports multi-line strings. Literal unescaped newlines are a syntax error.
// JSON does NOT support real multi-line strings.
// The following is INVALID:
// { "text": "line1
// line2" }
// Workaround 1: escape the newline
{ "text": "line1\nline2" }
// Workaround 2: array of lines
{ "lines": ["line1", "line2"] }
// Workaround 3: JSON5 allows continued strings (still single logical line)Common String Pitfalls
Common string errors: using single quotes, leaving trailing commas, forgetting to escape inner double quotes, and embedding literal control characters (tab/newline) instead of their \t/\n escapes. A strict parser rejects all of these.
// WRONG: single quotes
// { 'name': 'Alice' }
// WRONG: trailing comma
// { "a": 1, }
// WRONG: unescaped quote
// { "msg": "He said "hi"" }
// WRONG: literal tab/newline in string
// { "x": "a<TAB>b" }
// RIGHT:
{ "name": "Alice", "msg": "He said \"hi\"" }Numbers
Integer & Float
JSON has a single number type that covers integers and floating-point values. There is no separate integer type at the syntax level—language bindings may map large integers to int, long, float, or decimal depending on value and library.
{
"count": 100,
"negative": -42,
"temperature": -273.15,
"pi": 3.14159,
"zero": 0,
"negativeZero": -0
}
// Integers and floats use the same number type.
// JSON does not distinguish int from float at the syntax level.Scientific Notation
JSON supports scientific notation: a mantissa followed by e or E and an optional signed exponent (6.022e23 = 6.022 * 10^23). Both e and E are accepted. This is essential for very large or very small numbers in scientific data.
{
"avogadro": 6.022e23,
"planck": 6.626e-34,
"speedOfLight": 2.998e8,
"small": 1.5E-10
}
// e or E is allowed (case-insensitive).
// 6.022e23 means 6.022 * 10^23.
// The exponent may be negative.Number Precision
JSON numbers are typically parsed as IEEE 754 doubles, so integers above 2^53-1 (9007199254740991) lose precision in JavaScript. Decimal values like 0.1 cannot be represented exactly. For money or arbitrary-precision integers, encode them as strings and use a Decimal/BigInteger type in your code.
{
"big": 9007199254740993,
"decimal": 0.1,
"sum": 0.1,
"money": 19.99
}
// JavaScript stores numbers as IEEE 754 doubles.
// Integers are safe up to 2^53 - 1 (9007199254740991).
// 0.1 + 0.2 === 0.30000000000000004 (float precision loss).
// For money or big integers, parse as string or use a Decimal type.Special Values (Not Allowed)
Standard JSON does not allow NaN, Infinity, or -Infinity. Workarounds: use null for NaN, encode Infinity as a string, or use a finite sentinel value. Some serializers (Python's json by default, JSON5) emit these as extensions, but the output is non-standard and may be rejected by strict parsers.
// NaN, Infinity, and -Infinity are NOT valid JSON.
// INVALID:
// { "x": NaN }
// { "y": Infinity }
// { "z": -Infinity }
// Common workarounds:
{
"x": null, // represent NaN/null
"y": "Infinity", // encode as a string
"z": 1.7976931348623157e308 // use a finite max
}
// Many serializers (e.g., Python json) accept these as extensions
// but the output is not standard JSON.Number Formats
Valid JSON numbers: optional minus, integer part (no leading zeros except for 0), optional fractional part, optional exponent. Hex (0x), binary (0b), octal, underscores, leading +, leading zeros, and a dot without digits on both sides are all invalid.
// VALID JSON numbers:
42
-7
0
3.14
-0.5
6.022e23
1.5E-10
100.00
// INVALID:
007 // leading zero
.5 // no leading digit
5. // no trailing digit after dot
+5 // leading plus sign
0x1F // hex
0b101 // binary
1_000 // underscoresLarge Numbers & BigInt
For values above 2^53-1 (e.g., Twitter snowflake IDs, 64-bit integers, large balances), encode them as strings to avoid precision loss. If you must use a reviver in JSON.parse to convert numbers to BigInt, remember BigInt cannot be re-serialized by JSON.stringify without a replacer—strings are safer on the wire.
{
"snowflake": "1234567890123456789",
"timestamp": 1696000000000,
"balance": "99999999999999999999"
}
// Numbers above 2^53-1 lose precision in JS.
// Use STRINGS for IDs, snowflakes, and big integers.
// In JavaScript, parse with a reviver:
// JSON.parse(str, (k, v) =>
// typeof v === "number" && v > Number.MAX_SAFE_INTEGER
// ? BigInt(v) : v); // careful: BigInt can't be in JSON.stringify
// Better: keep them as strings on the wire.Booleans & Null
Boolean Values
JSON booleans are the bare keywords true and false. Quoted 'true'/'false' are strings. JSON has no concept of truthy/falsy at the syntax level—1, 0, yes, no, on, off are all strings or numbers, not booleans. Convert them in application code.
{
"enabled": true,
"disabled": false,
"isPublic": true,
"isActive": false
}
// Only two boolean values: true and false (lowercase, unquoted).
// "true" (quoted) is a STRING, not a boolean.
// 1/0, yes/no, on/off are NOT booleans.Null Meaning
JSON null signals the intentional absence of a value. It is distinct from a missing key (key not in the object), an empty string '', 0, false, or an empty collection. Use null when a field exists but has no value; omit the key when the field itself does not apply.
{
"middleName": null,
"deletedAt": null,
"parent": null,
"optional": null
}
// null means "no value" or "intentionally absent".
// Distinct from:
// - missing key (key not present at all)
// - empty string ""
// - 0 or false
// - empty array [] or object {}Null vs Empty vs Missing
Three distinct states: a key with an empty value (""), a key explicitly null, and a missing key. In JavaScript, undefined means the key is absent while null means it is present but has no value. APIs should document which convention they use for optional fields.
{
"name": "Alice",
"nickname": "", // empty string (present, empty)
"middleName": null, // explicit null (present, no value)
// "maidenName" // missing (key not in object)
}
// In JavaScript:
// obj.nickname === "" // true
// obj.middleName === null // true
// obj.maidenName === undefined // true (key absent)
// "maidenName" in obj // false
// Choose deliberately: null vs "" vs missing.Using Booleans in Conditions
When consuming JSON booleans, prefer strict comparison (=== true) over truthy checks if you need to distinguish false from missing. In API responses, always include boolean fields even when false—omitting them forces clients to guess the default.
{
"isAdmin": true,
"canEdit": false,
"active": true
}
// In application code (JavaScript):
// if (user.isAdmin) { ... } // truthy check
// const canEdit = user.canEdit === true; // strict boolean check
// Be careful: a missing 'canEdit' key is undefined (falsy),
// but explicit false is also falsy. Distinguish if needed.
// API design: always send the boolean, even when false.Common Pitfalls
Common pitfalls: quoting true/false/null turns them into strings; using True/TRUE/None (Python) or true/false with wrong case is invalid; JSON has no undefined (only null). The only valid forms are the lowercase unquoted keywords true, false, and null.
// Pitfall 1: quoting booleans/null
// { "x": "true" } -> x is a STRING, not a boolean
// { "y": "null" } -> y is a STRING, not null
// Pitfall 2: wrong case
// { "x": True } -> INVALID (Python-style, not JSON)
// { "x": TRUE } -> INVALID
// { "x": None } -> INVALID
// Pitfall 3: confusing null with undefined
// null exists in JSON; undefined does NOT.
// Correct:
{ "x": true, "y": null }Arrays
Array Basics
JSON arrays are ordered, zero-indexed lists wrapped in [ ], with comma-separated values. Empty arrays and single-element arrays are valid. Order is significant and preserved by parsers. There is no trailing comma allowed.
{
"numbers": [1, 2, 3, 4, 5],
"strings": ["a", "b", "c"],
"booleans": [true, false, true],
"empty": [],
"single": [42]
}
// Arrays are ordered, zero-indexed lists in [ ].
// Elements are separated by commas (no trailing comma).
// Empty arrays [] and single-element arrays are valid.Mixed Type Arrays
JSON arrays can legally hold mixed types ([1, 'two', true, null]). This is valid but often indicates weak schema design. Homogeneous arrays (all strings, all objects) are easier to validate, document, and consume. Use a schema to enforce element types.
{
"mixed": [1, "two", true, null, 3.14],
"nested": [[1, 2], "x", { "a": 1 }]
}
// JSON arrays CAN hold values of different types.
// This is valid but often a sign of weak schema design.
// Prefer homogeneous arrays for clarity and validation.Nested Arrays
Arrays can nest to any depth, useful for matrices, grids, and tree structures. JSON does not enforce that nested arrays have equal length (a 'ragged' array is valid). If you need a rectangular matrix, enforce it with a schema or application code.
{
"matrix": [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
"ragged": [[1, 2], [3, 4, 5], [6]]
}
// Arrays can nest arbitrarily deep.
// JSON does not enforce rectangular shape—use a schema if needed.Array of Objects
An array of objects is the most common pattern for lists of records (users, products, posts). Each element typically has the same shape, but JSON does not enforce this—use a schema (JSON Schema 'items') to validate that all elements conform.
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Carol" }
],
"empty": []
}
// A very common pattern: a list of records.
// Each element is an object with the same shape.Empty and Single-element Arrays
Empty arrays [] and single-element arrays are valid. In API design, distinguish [] (present, empty list) from null (present, no list) and a missing key (field not applicable). Returning [] for 'no items' is usually friendlier than null.
{
"empty": [],
"single": [42],
"tags": [],
"items": ["one"]
}
// Both forms are valid.
// Distinguish [] from null and from a missing key:
// "tags": [] -> present, empty list
// "tags": null -> present, no list
// // (no tags) -> missing keyArray Access in Code
After parsing, JSON arrays become native arrays/lists in your language (JS Array, Python list, Java List, etc.). Use standard index access, length, and iteration. Bounds and type safety are your responsibility—JSON itself does not enforce element types.