一、JSON的核心方法:数据转换的"双刃剑"
-
JSON.parse():字符串→对象的魔法
JSON.parse()
方法接受一个 JSON 字符串作为参数,并返回一个对应的 JavaScript 对象。 语法:
javascript
JSON.parse(text[, reviver])
text
(必需): 要解析为 JavaScript 对象的 JSON 字符串。reviver
(可选): 一个函数,用于转换结果。该函数接收两个参数:键和值。它应该返回要添加到 JavaScript 对象中的值。
javascript
const jsonString = '{"name":"John Doe","age":30,"city":"New York"}';
const person = JSON.parse(jsonString);
console.log(person); // 输出: {name: "John Doe", age: 30, city: "New York"}
console.log(person.name); // 输出: John Doe
// 使用 reviver 函数
const personWithReviver = JSON.parse(jsonString, (key, value) => {
if (key === "age") {
return value + 5; // 将 age 增加 5
}
return value;
});
console.log(personWithReviver); // 输出: {name: "John Doe", age: 35, city: "New York"}
• 关键点 :自动处理嵌套结构,但需警惕格式错误(如单引号、尾逗号)导致的SyntaxError
。
• 安全解析 :用try-catch
包裹避免崩溃:
javascript try { JSON.parse(invalidJson); } catch (e) { console.error("JSON格式错误!", e); }
-
JSON.stringify():对象→字符串的奥秘
语法:javascriptJSON.stringify(value[, replacer[, space]])
-
value
(必需): 要转换为 JSON 字符串的 JavaScript 对象。 -
replacer
(可选): 一个函数或数组,用于转换结果。- 函数: 该函数接收两个参数:键和值。它应该返回要添加到 JSON 字符串中的值。如果返回
undefined
,则该键值对将被排除。 - 数组: 一个字符串数组,指定要包含在 JSON 字符串中的键。
- 函数: 该函数接收两个参数:键和值。它应该返回要添加到 JSON 字符串中的值。如果返回
-
space
(可选): 一个字符串或数字,用于在 JSON 字符串中添加空格以提高可读性。- 数字: 表示要使用的空格数。
- 字符串: 表示要使用的空格字符串(最多 10 个字符)。
javascriptconst user = { name: "小明", skills: ["JS", "Python"] }; const jsonStr = JSON.stringify(user); // 输出:{"name":"小明","skills":["JS","Python"]}
• 进阶格式化:添加缩进提升可读性(适合日志/调试):
javascriptJSON.stringify(user, null, 4); // 4空格缩进
• 数据过滤 :通过
replacer
参数隐藏敏感字段(如密码):javascriptJSON.stringify(user, (k, v) => k === 'password' ? undefined : v);
-
二、高阶技巧:解锁JSON的"隐藏技能"
-
深度克隆对象:打破引用的枷锁
javascriptconst original = { a: 1, nested: { b: 2 } }; const clone = JSON.parse(JSON.stringify(original)); clone.nested.b = 99; console.log(original.nested.b); // 仍为2
• 局限性 :无法复制函数、
undefined
及循环引用对象。 -
自定义序列化:用toJSON()掌控输出
为自定义类定义序列化逻辑:
javascriptclass User { constructor(name) { this.name = name; } toJSON() { return { name: this.name.toUpperCase() }; } } console.log(JSON.stringify(new User("john"))); // {"name":"JOHN"}
• 应用场景:简化复杂对象(如日期格式、加密数据)。