⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

JavaScript JSON 处理

学习 JSON.stringify 和 JSON.parse · 难度:入门 · +10XP

JavaScript JSON 数据处理完全指南

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,基于 JavaScript 对象字面量语法,但独立于编程语言。JSON 已成为 Web 开发中前后端数据交换的通用标准格式。JavaScript 内置了 JSON.parse()JSON.stringify() 方法进行 JSON 数据的解析和序列化。

JSON 语法规则

  1. 数据以键值对形式存在:{"key": "value"}
  2. 键必须用双引号包裹(单引号无效)
  3. 值可以是:字符串、数字、布尔值、数组、对象、null
  4. 不支持:函数、undefined、NaN、Infinity、Date 对象
  5. 不支持尾随逗号(trailing comma)
// 合法的 JSON 示例
{
  "name": "张三",
  "age": 25,
  "isStudent": false,
  "hobbies": ["读书", "编程", "运动"],
  "address": {
    "city": "北京",
    "zip": "100000"
  },
  "score": null
}

JSON.parse() 解析 JSON

参数说明示例
text要解析的 JSON 字符串'{"a":1}'
reviver可选,转换函数 (key, value) => newValue(k,v) => k === "date" ? new Date(v) : v
// 基本解析
const jsonStr = '{"name":"张三","age":25,"skills":["JS","Python"]}';
const obj = JSON.parse(jsonStr);
console.log(obj.name);   // "张三"
console.log(obj.skills); // ["JS", "Python"]

// 使用 reviver 函数转换数据 const dateJson = '{"name":"会议","date":"2026-05-30T10:00:00Z"}'; const event = JSON.parse(dateJson, (key, value) => { // 将日期字符串转换为 Date 对象 if (key === "date") return new Date(value); return value; }); console.log(event.date instanceof Date); // true console.log(event.date.toLocaleString("zh-CN"));

JSON.stringify() 序列化对象

const user = {
  name: "张三",
  age: 25,
  password: "secret123",
  roles: ["admin", "user"],
  meta: null
};

// 基本序列化 const json = JSON.stringify(user); console.log(json); // {"name":"张三","age":25,"password":"secret123","roles":["admin","user"],"meta":null}

// 使用 replacer 过滤属性(数组方式) const safe = JSON.stringify(user, ["name", "age", "roles"]); // {"name":"张三","age":25,"roles":["admin","user"]} // password 被过滤!

// 使用 replacer 函数动态控制 const filtered = JSON.stringify(user, (key, value) => { if (key === "password") return undefined; // 排除密码 return value; }); console.log(filtered); // {"name":"张三","age":25,"roles":["admin","user"],"meta":null}

// 美化输出(space 参数) console.log(JSON.stringify(user, null, 2)); // { // "name": "张三", // "age": 25, // ... // }

JSON 错误处理与边界情况

// JSON.parse 可能抛出 SyntaxError
function safeParse(str, fallback = null) {
  try {
    return JSON.parse(str);
  } catch (err) {
    console.error("JSON 解析失败:", err.message);
    return fallback;
  }
}

// 处理不规范的 JSON console.log(safeParse("invalid")); // null console.log(safeParse('{"a":1}')); // { a: 1 } console.log(safeParse('{"a":1,}')); // null(尾随逗号不合法!)

// 深拷贝:JSON 方式的深拷贝(有局限性) const original = { a: 1, b: { c: 2 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.b.c = 999; console.log(original.b.c); // 2(未被修改)

// 注意:JSON 深拷贝的局限性 const obj = { date: new Date(), // 会变成字符串 fn: function() {}, // 会被丢弃 undef: undefined, // 会被丢弃 reg: /test/g, // 会变成空对象 {} nan: NaN // 会变成 null }; console.log(JSON.parse(JSON.stringify(obj))); // 推荐:使用 structuredClone() 进行真正的深拷贝

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0