Skip to content

JSON

学习 JSON — 数据格式那个 APIs use 到 exchange 信息之间客户端 and 服务器.

你将学到

  • 什么 JSON 是 and 为什么它 replaced XML
  • JSON's six 数据类型 and 它的语法规则
  • 如何 parse and stringify JSON in JavaScript
  • 常见 pitfalls 如 trailing commas and 单个 quotes

概念讲解

JSON

JSON (JavaScript Object Notation) is a lightweight, text-based format for exchanging data. It is the lingua franca of web APIs — when a server sends data to a browser, it almost always sends JSON. Despite the name, JSON is language-independent; nearly every language can read and write it.

Syntax and Types

JSON is built from six data types:

{
  "name": "Ada",           // string (must use double quotes)
  "age": 36,               // number
  "isAdmin": true,         // boolean
  "spouse": null,          // null
  "hobbies": ["math", "code"],  // array
  "地址": {             // object
    "city": "London",
    "zip": "NW1"
  }
}

Strict Rules

JSON is stricter than JavaScript object literals:

  • Keys must be in double quotes. Single quotes are invalid.
  • Strings must use double quotes. No single quotes.
  • No trailing commas. {"": 1,} is a syntax error.
  • No comments. // and /* */ are not allowed.
  • No functions or undefined. Only data, never code.

These rules make JSON unambiguous to parse. They also trip up beginners who copy JavaScript syntax into a JSON file.

Parsing in JavaScript

const text = '{"name": "Ada", "age": 36}';
const obj = JSON.parse(text);     // string → object
console.log(obj.name);            // "Ada"

const json = JSON.stringify(obj); // object → string

JSON.parse throws on invalid syntax, so wrap it in try/catch when handling untrusted input.

Why JSON Won

JSON replaced XML for APIs because it is smaller (no closing tags), faster to parse, and maps directly to the objects and arrays programmers already use. It is not better at everything — XML still shines for documents with mixed content — but for data exchange, JSON is the default.

示例代码

              // A typical API response in JSON
const apiResponse = `{
  "users": [
    { "id": 1, "name": "Ada", "role": "admin" },
    { "id": 2, "name": "Grace", "role": "editor" }
  ],
  "total": 2,
  "page": 1
}`;

// Parse and use it
const data = JSON.parse(apiResponse);
const adminNames = data.users
  .filter(u => u.role === "admin")
  .map(u => u.name);

console.log(adminNames);  // ["Ada"]

// Convert back to JSON (with pretty-printing)
const pretty = JSON.stringify(data, null, 2);
console.log(pretty);
            

JSON.parse turns 字符串到 JavaScript 对象你 能 manipulate 使用 normal 数组方法. JSON.stringify 使用 indent 实参 produces readable, pretty-printed JSON.

动手试一试

常见错误

错误写法

Using 单个 quotes or trailing commas in JSON.

正确做法

JSON 需要双 quotes for 键 and 字符串, and forbids trailing commas. Use JSON validator 到 catch 这些 — 错误消息点 到精确位置.

错误写法

Calling JSON.parse 不使用 try/catch on untrusted 输入.

正确做法

JSON.parse throws on 无效语法. Wrap 它 in try/catch and handle 错误 gracefully, or 你的整个 app 将 crash on malformed 输入.

相关速查表

相关指南

练习 JSON

9 个练习

练习 JSON

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误