入门
基本结构
JSON 支持 6 种数据类型:字符串、数字、布尔、null、数组和对象。键必须是双引号字符串。JSON 与语言无关,人和机器都易于读写。
{
"name": "Alice",
"age": 30,
"isStudent": false,
"height": 1.65,
"nullValue": null,
"hobbies": ["reading", "coding", "music"],
"address": {
"city": "NYC",
"zip": "10001"
}
}JSON 语法规则
JSON 语法严格:键和字符串只能用双引号,逗号分隔元素,禁止尾随逗号。整个文档必须是单个 JSON 值。标准 JSON 不支持注释——如需注释,使用预处理器或 JSON5。
{
"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 JSONJSON 中的注释
标准 JSON 禁止注释。常见变通方法:添加 '_comment' 字段(代码忽略)、使用 JSONC/JSON5(VS Code 等工具支持),或用 comment-json、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)空白与格式化
字符串外的空白无意义——紧凑形式和美化形式解析结果相同。紧凑 JSON 节省带宽;美化形式(常用 2 空格缩进)提升可读性和 diff 友好度。大多数序列化器提供 'pretty' 选项。
// 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.文件扩展名与 MIME 类型
标准扩展名是 .json,MIME 类型是 application/json。JSONC、JSON5、GeoJSON、NDJSON 等变体有各自约定。始终使用 UTF-8 编码,不推 荐使用 BOM。
// 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 值类别
JSON 值分为六种类型:字符串、数字、布尔、null、数组、对象。数组和对象是结构化类型(可容纳其他值),其余是基元类型。合法的 JSON 文档是一个值——通常是对象或数组,但单独的数字或字符串也合法。
// 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.数据类型
字符串类型
JSON 字符串是双引号包裹的 Unicode 文本。常见转义:\"(引号)、\\(反斜杠)、\/(斜杠)、\n、\t、\r、\b、\f,以及任意码点的 \uXXXX。不允许用单引号作为字符串分隔符。
{
"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.数字类型
JSON 数字遵循 IEEE 754 双精度的子集:整数、小数和科学计数法(如 6.022e23)。禁止前导零(007 非法)。NaN、Infinity、-Infinity 不合法——需要时用 null 或字符串表示。
{
"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).布尔类型
JSON 布尔是字面关键字 true 和 false(小写、不加引号)。加引号的 'true'/'false' 是字符串。JSON 语法层没有 0/1 或 yes/no 作为布尔的概念——需要在应用代码中转换。
{
"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 类型
JSON null 是字面关键字 null(不加引号),表示有意缺失值。它不同于空字符串 ''、0、false、缺失键或空集合。许多语言将 null 映射为 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.数组类型
JSON 数组是 [ ] 包裹的有序列表,逗号分隔,从 0 开始索引。可容纳任意 JSON 值,包括混合类型和嵌套数组/对象。空数组 [] 合法。顺序被保留且有意义。
{
"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.对象类型
JSON 对象是 { } 包裹的无序键值对集合。键必须是唯一的双引号字符串;值可以是任意 JSON 类型。虽然对象概念上无序,但大多数解析器保留插入顺序——不要依赖顺序做正确性保证。
{
"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.字符串
字符串基础
JSON 字符串是双引号包裹的 Unicode 字符序列。正斜杠可转义(\/)但非必须——在 <script> 标签中嵌入 JSON 时有用。空字符串合法。
{
"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.转义序列
JSON 支持这些转义:\"(引号)、\\(反斜杠)、\/(斜杠)、\b(退格)、\f(换页)、\n(换行)、\r(回车)、\t(制表符)、\uXXXX(Unicode 码点)。其他反斜杠序列均非法。
{
"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 字符
用 \uXXXX 表示任意 Unicode 码点。U+FFFF 以上的字符(如许多 emoji)需要代理对:两 个 \u 转义。现代解析器也接受原始 UTF-8 字符直接出现在字符串中——\uXXXX 主要用于安全或无法输入字符时。
{
"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.字符串中的特殊字符
JSON 字符串内必须始终转义双引号和反斜杠(\" 和 \\)。其他特殊字符(HTML、SQL、正则)遵循各自规则,但 JSON 只要求转义 \" 和 \\(以及控制字符)。字面反斜杠写作 \\。
{
"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 \\.多行字符串(变通方案)
JSON 字符串不能包含字面换行——必须转义为 \n。多行内容可嵌入 \n、使用行字符串数组,或改用 YAML/JSON5 等支持多行字符串的格式。字面未转义换行是语法错误。