40. 实现一个 JSON.stringify 副本.md

查看飞书原文 ↗3,212 字符

1. 核心概念 (Core Concept)

JSON.stringify() 是 JavaScript 内置的用来将 JavaScript 值(对象、数组、基本类型等)转换成 JSON 格式字符串的方法。JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。

2. 为什么需要它? (The "Why")

3. API 与用法 (API & Usage)

JSON.stringify() 方法的语法如下:

JSON.stringify(value[, replacer[, space]])

核心转换规则:

代码示例 (来自 MDN Web Docs):

基本用法:

const obj = {
  a: 1,
  b: [2, 3],
  c: 'hello',
  d: true,
  e: null,
  f: undefined, // 会被忽略
  g: function() {} // 会被忽略
};

console.log(JSON.stringify(obj));
// Output: {"a":1,"b":[2,3],"c":"hello","d":true,"e":null}

使用 replacer 数组:

const obj = {
  a: 1,
  b: 2,
  c: 3
};

console.log(JSON.stringify(obj, ['a', 'c']));
// Output: {"a":1,"c":3}

使用 replacer 函数:

const obj = {
  a: 1,
  b: 2,
  c: 'sensitive data'
};

console.log(JSON.stringify(obj, (key, value) => {
  if (key === 'c') {
    return 'redacted';
  }
  return value;
}));
// Output: {"a":1,"b":2,"c":"redacted"}

使用 space 进行格式化:

const obj = {
  a: 1,
  b: 2,
  c: {
    d: 3
  }
};

console.log(JSON.stringify(obj, null, 2));
/* Output:
{
  "a": 1,
  "b": 2,
  "c": {
    "d": 3
  }
}
*/

4. 关键注意事项 (Key Considerations)

5. 参考资料 (References)


原文链接与附件索引