发布于 2026-09-17 · CATAITO

JSON 入门与实用技巧

从语法规范到常见错误排查,再到 YAML/TOML/CSV 的取舍。附免费在线 JSON 格式化器。

JSON 是什么

JSON(JavaScript Object Notation)是 RFC 8259 定义的一种轻量级数据交换格式。它的核心优势是几乎所有现代语言都有原生支持——JavaScript、Python、Java、Go、Rust、Swift……都能一行代码解析或序列化。

典型结构长这样:

{
  "name": "CATAITO",
  "tools": 16,
  "free": true,
  "tags": ["web", "privacy"],
  "nested": { "localOnly": true }
}

JSON 不是 JSONP、不是 JavaScript、不是任何编程语言。它是一种格式,跟 HTML、XML 同属数据交换的「语法规则」,本身不含逻辑。这也意味着,只要遵守这套规则,任何两个实现之间的数据都能互换。

支持的数据类型

JSON 只认 7 种类型,比 JavaScript 少得多:

类型示例说明
object{"k": "v"}无序键值对,键必须是字符串
array[1, 2, 3]有序值列表
string"hello"UTF-8 编码,必须用双引号
number42 / -3.14整数或浮点,无符号
booleantrue / false只有两个值
nullnull显式的「空值」
不支持:undefined、function、Date、Map、Set、RegExp、Symbol

没有 Date 类型是很多人踩的第一个坑:new Date() 在 JS 里是原生对象,但 JSON.stringify(new Date()) 会输出 ISO 字符串(因为 Date.prototype.toJSON 被覆盖了)。反过来,JSON.parse 遇到 ISO 字符串不会自动还原成 Date,需要应用层自己做转换。

常见语法错误

JSON 解析报错时,90% 是以下几种: 用本站 JSON 格式化器 可以直接看到错误位置和原因。

  1. 尾随逗号:[1, 2, 3,] 或 {"a": 1,} 都不合法。Python/JS 允许,JSON 不允许。
  2. 单引号字符串:{"name": 'Alice'} 不合法。JSON 只认双引号。
  3. 未加引号的键:{name: "Alice"} 不合法。JS 对象字面量允许,JSON 不允许。
  4. 注释:{"a": 1 /* comment */} 不合法。JSON 没有注释语法。
  5. undefined / NaN:{"a": undefined} 或 {"a": NaN} 不合法。要表达「无值」用 null。
  6. 引号嵌套未转义:"say "hi"" 会解析失败。内层双引号必须写成 "say \"hi\""。

与 JavaScript 对象的区别

「JSON 就是 JS 对象」是常见误解。它们在语法上严格区分:

方面JSONJS 对象字面量
键的引号必须双引号 "a"可省略 a,或单/双引号
尾随逗号禁止允许
注释禁止允许 // / /* */
键类型只能字符串可任意值(会被转字符串)
值类型7 种标准类型任意 JS 值,含函数、undefined
解析器JSON.parse()eval()(危险)或不需解析

所以从 JS 对象生成 JSON,必须走 JSON.stringify(obj),不能直接把对象字面量当字符串塞进 HTTP 响应。反过来,从 JSON 字符串恢复成 JS 对象,必须走 JSON.parse(str),不要用 eval()——后者能执行任意代码,是安全漏洞。

与 YAML / TOML / CSV 对比

四种常见的数据格式,适用场景不同:

格式定位优势劣势
JSON机器对机器原生支持广泛、无歧义、生态成熟无注释、无引用、人写易错
YAML人写配置语法简洁、支持注释/锚点/多文档解析歧义多、缩进敏感
TOML严格配置语法严、类型明确、语法糖少嵌套深时冗长、生态弱于 YAML
CSV表格数据极简、任何表格软件都能读无嵌套、无类型、易解析出错

选择原则:接口、日志、存储用 JSON;配置文件用 YAML 或 TOML(YAML 生态更成熟,TOML 语法更严格);纯表格数据用 CSV。混用是常见错误——比如把 CSV 当配置存下来,遇到字段里有逗号、换行符、引号就会崩。

实用技巧与坑

转义与编码

JSON 字符串里,"、\、控制字符(\n、\t、\r)必须转义;非 ASCII 字符可以用 UTF-8 直接写,也可以用 \uXXXX 表示。中文一般直接写 UTF-8 就好,除非目标环境不支持 UTF-8。

大文件与流式

单次 JSON.parse 一个 50MB 的文件会卡死主线程。大数据场景用流式解析:JSON Lines(一行一个 JSON 对象,逐行 parse)是常见做法,Kafka、Elasticsearch 等都用这个格式。

序列化时的 undefined 陷阱

JSON.stringify({a: undefined, b: null, c: 1}) 输出 {"b":null,"c":1}——undefined 字段会被静默丢弃,null 会保留。如果你依赖「缺字段」和「字段为 null」的语义区分,要格外小心。

数字精度

JSON number 没有整数/浮点区分。JS 的 number 是 64-bit IEEE 754,超过 2^53 会丢精度。处理雪花 ID、雪花 ID 变体或任意精度数字时,建议序列化为字符串:

{"id": "12345678901234567890"}  // 字符串,安全
{"id": 12345678901234567890}   // 数字,可能变成 12345678901234567000

校验 schema

JSON 规范只管语法,不管结构。要校验「某个 JSON 是否符合约定结构」,用 JSON Schema 或运行时库(如 Python 的 pydantic、JS 的 zod)。这是生产环境必备的防御层。

常见问题

Q:JSON 和 JavaScript 对象有什么区别?

A:JSON 是 RFC 8259 定义的数据格式,JavaScript 对象是 JS 语言内的数据结构。JSON 要求键必须用双引号包裹,不允许尾随逗号、单引号字符串、注释或未加引号的键;JavaScript 对象字面量允许这些形式。JSON.parse 只接受严格 JSON。

Q:JSON 支持哪些数据类型?

A:RFC 8259 定义 7 种:对象、数组、字符串、数字、布尔、null。没有 undefined、函数、Date、Map 或 Set 类型。

Q:JSON 键的顺序有保证吗?

A:规范明确对象成员无序,解析器可以重排。实际引擎多数保留插入顺序,但不是规范保证,不能依赖。

Q:JSON 文件大小有限制吗?

A:RFC 本身不设上限,限制来自实现方。浏览器 JSON.parse 通常能处理到 50MB 级;HTTP 传输受服务器请求体限制(Nginx 默认 1MB);REST API 常见限 1-10MB。

Q:JSON 能直接表示时间戳、日期、二进制吗?

A:不能。约定做法:时间用 ISO 8601 字符串或时间戳数字;二进制用 Base64 字符串加 MIME 类型标注。

Q:什么时候该用 YAML/TOML 而不是 JSON?

A:YAML/TOML 面向「人读人写」的配置场景;JSON 面向「机器对机器」的数据交换。配置用 YAML/TOML,接口/存储/日志用 JSON。

免费格式化 / 校验 / 压缩 JSON

粘贴即校验 · 缩进 2/4/Tab 可选 · 错误定位到行列 · 纯浏览器本地处理

打开 JSON 格式化器 →

What JSON Is

JSON (JavaScript Object Notation) is a lightweight data-exchange format defined by RFC 8259. Its core advantage: nearly every modern language has native support — JavaScript, Python, Java, Go, Rust, Swift all parse and serialize it in one line.

Typical structure:

{
  "name": "CATAITO",
  "tools": 16,
  "free": true,
  "tags": ["web", "privacy"],
  "nested": { "localOnly": true }
}

JSON is not JSONP, not JavaScript, not any programming language. It's a format — a grammar of data exchange, parallel to HTML and XML — with no logic of its own. As long as both sides follow the rules, data interoperates.

Supported Data Types

JSON knows only seven types, far fewer than JavaScript:

TypeExampleNotes
object{"k": "v"}Unordered key-value pairs; keys must be strings
array[1, 2, 3]Ordered list of values
string"hello"UTF-8 encoded, must use double quotes
number42 / -3.14Integer or float, no sign
booleantrue / falseTwo values only
nullnullExplicit "no value"
Not supported: undefined, function, Date, Map, Set, RegExp, Symbol

The absence of Date is a common first stumble: new Date() is a native object in JS, but JSON.stringify(new Date()) outputs an ISO string (because Date.prototype.toJSON is overridden). Conversely, JSON.parse given an ISO string does not restore a Date; your application must convert it.

Common Syntax Errors

When JSON parsing fails, 90% of the time it's one of the following. Use the JSON Formatter to see error positions and reasons.

  1. Trailing commas: [1, 2, 3,] or {"a": 1,} are invalid. Python/JS allow them, JSON does not.
  2. Single-quoted strings: {"name": 'Alice'} is invalid. JSON only accepts double quotes.
  3. Unquoted keys: {name: "Alice"} is invalid. JS object literals allow it, JSON does not.
  4. Comments: {"a": 1 /* comment */} is invalid. JSON has no comment syntax.
  5. undefined / NaN: {"a": undefined} or {"a": NaN} are invalid. Use null for "no value".
  6. Unescaped nested quotes: "say "hi"" will fail. Escape the inner quotes: "say \"hi\"".

JSON vs JavaScript Objects

"JSON is just a JS object" is a common misconception. They differ strictly in syntax:

AspectJSONJS Object Literal
Key quotingMust use double quotes "a"Can omit a, or single/double quotes
Trailing commasForbiddenAllowed
CommentsForbiddenAllowed // / /* */
Key typesString onlyAny value (coerced to string)
Value types7 standard typesAny JS value, including functions, undefined
ParserJSON.parse()eval() (dangerous) or no parsing needed

So to generate JSON from a JS object, always use JSON.stringify(obj) — never drop the object literal into an HTTP response as a string. Conversely, to restore a JS object from JSON, use JSON.parse(str), never eval() — the latter executes arbitrary code and is a security hole.

JSON vs YAML / TOML / CSV

Four common data formats with distinct purposes:

FormatPositioningStrengthsWeaknesses
JSONMachine ↔ machineUbiquitous native support, no ambiguity, mature ecosystemNo comments, no references, easy for humans to typo
YAMLHuman-authored configConcise syntax, comments, anchors/aliases, multi-docParser ambiguity, indent-sensitive
TOMLStrict configStrict syntax, clear types, less syntactic sugarVerbose when deeply nested, smaller ecosystem than YAML
CSVTabular dataMinimal, any spreadsheet reads itNo nesting, no types, easy to mis-parse

Rule of thumb: interfaces, logs, storage use JSON; config files use YAML or TOML (YAML has a larger ecosystem, TOML has stricter syntax); pure tabular data uses CSV. Mixing is a common mistake — e.g., treating CSV as config breaks as soon as a field contains commas, newlines, or quotes.

Practical Tips & Gotchas

Escaping and encoding

In JSON strings, ", \, and control characters (\n, \t, \r) must be escaped. Non-ASCII characters can be written directly as UTF-8, or via \uXXXX. Chinese generally works as UTF-8 unless the target environment doesn't support it.

Large files and streaming

A single JSON.parse on a 50MB file freezes the main thread. For large data, use streaming parsers: JSON Lines (one JSON object per line, parse line-by-line) is a common pattern — used by Kafka, Elasticsearch, etc.

The undefined trap in serialization

JSON.stringify({a: undefined, b: null, c: 1}) outputs {"b":null,"c":1} — the undefined field is silently dropped, null is preserved. If you depend on the distinction between "field missing" and "field is null", be careful.

Number precision

JSON numbers have no integer/float distinction. JS numbers are 64-bit IEEE 754; values above 2^53 lose precision. For snowflake IDs and arbitrary-precision numbers, serialize as strings:

{"id": "12345678901234567890"}  // String, safe
{"id": 12345678901234567890}   // Number, may become 12345678901234567000

Schema validation

The JSON spec handles only syntax, not structure. To validate that a JSON conforms to a shape, use JSON Schema or a runtime library (e.g., Python's pydantic, JS's zod). This is a required defense layer in production.

FAQ

Q: What's the difference between JSON and JavaScript objects?

A: JSON is a data format defined by RFC 8259; JavaScript objects are a JS-language data structure. JSON requires double-quoted keys, disallows trailing commas, single-quoted strings, comments, and unquoted keys. JSON.parse accepts strict JSON only.

Q: What data types does JSON support?

A: RFC 8259 defines seven: object, array, string, number, boolean, null. No undefined, function, Date, Map, or Set.

Q: Is JSON key order guaranteed?

A: The spec explicitly says object members are unordered; parsers may reorder. Most modern engines preserve insertion order, but this is not a spec guarantee, so don't rely on it.

Q: Is there a file-size limit for JSON?

A: RFC itself sets no limit; limits come from implementations. Browser JSON.parse typically handles up to ~50MB; HTTP transfer is bounded by server request-body limits (Nginx defaults to 1MB); REST APIs commonly cap at 1-10MB.

Q: Can JSON represent timestamps, dates, and binary directly?

A: No. Conventions: use ISO 8601 strings or numeric timestamps for time; Base64 strings plus a MIME type for binary.

Q: When should I use YAML/TOML instead of JSON?

A: YAML/TOML target human-written config; JSON targets machine-to-machine data exchange. Use YAML/TOML for config, JSON for interfaces/storage/logs.

Free JSON Formatter / Validator / Minifier

Paste-to-validate · 2/4/Tab indent · Error line & column · 100% browser-local

Open JSON Formatter →