工具函数 · 53/107
1. 抽象工厂模式 2. Adapter Pattern 3. Adapter Pattern 4. 实现一个支持柯里化的 add 函数 5. 计算两个数组的交集 6. 数组中的数据根据key去重 7. 实现一个add方法完成两个大数相加 8. 大数相加 9. bind、call、apply 的区别与实现 10. Bridge Pattern 11. Builder Pattern 12. 实现一个管理本地缓存过期的函数 13. 缓存代理 14. 转化为驼峰命名 15. 实现 (5).add(3).minus(2) 功能 16. 咖啡机进阶优化 17. 咖啡机状态管理 18. 常用设计模式总结 19. 咖啡机状态切换机制 20. 查找数组公共前缀(美团) 21. 实现一个compose函数 22. 并发请求调度器 23. 组合模式 24. 实现 console.log 代理方法 25. Decorator Pattern 26. 实现防抖和节流 27. 实现一个JS函数柯里化 28. 实现防抖函数(debounce) 29. Decorator Pattern 30. 手写深度比较isEqual 31. 消除 if-else 条件判断 32. 修改嵌套层级很深对象的 key 33. 设计模式应用 34. 验证是否是邮箱 35. 实现发布订阅模式 36. 外观模式 37. Facade Pattern 38. Factory Pattern 39. 工厂模式 40. 工厂模式实现 41. Flyweight Pattern 42. 前端常用设计模式与场景 43. 提取对象中所有value大于2的键值对 44. 用正则实现根据name获取cookie中的值 45. 获取今天的日期 46. ES6 之前的迭代器模式 47. 实现 getValue/setValue 函数来获取path对应的值 48. 验证是否是身份证 49. 迭代器模式 50. jQuery slideUp 动画队列堆积问题 51. 实现一个JSON.parse 52. 实现 LazyMan 任务队列 53. 实现一个JSON.stringify 54. 实现lodash的chunk方法--数组按指定长度拆分 55. 字符串最长的不重复子串 56. LRU 缓存算法 57. 查找字符串中出现最多的字符和个数 58. new 操作符的实现原理 59. 中介者模式 60. 中介者模式 61. 对象数组如何去重 62. 千分位格式化 63. 实现观察者模式 64. 观察者模式实例 65. 观察者模式 66. 实现观察者模式 67. 实现 padStart() 和 padEnd() 的 Polyfill 68. 判断是否是电话号码 69. Proxy Pattern 70. 代理模式:婚介所 71. Proxy Pattern 72. 代理模式 73. 实现上拉加载和下拉刷新 74. 生成随机数组并排序 75. 大文件断点续传实现 76. 使用 setInterval 模拟实现 setTimeout 77. 重构询价逻辑 78. 实现一个简单的路由 79. setTimeout 模拟实现 setInterval 80. RGB 转 Hex 颜色转换 81. setTimeout与setInterval实现 82. Simple Factory Pattern 83. 实现单例模式 84. 实现一个 sleep 函数 85. 状态模式 86. State Pattern 87. 策略模式 88. Strategy Pattern 89. Storage 单例封装 90. 策略模式 91. 计算字符串字节长度 92. 字符串压缩算法实现 93. 字符串查找 94. 字符串去除前后空格 95. 实现模板引擎 96. 实现千位分隔符 97. 实现模板字符串解析功能 98. 实现一个函数判断数据类型 99. Promise 实现红绿灯交替 100. 实现节流函数(throttle) 101. 从指定数据源生成长度为 n 的不重复随机数组 102. 解析 URL Params 为对象 103. URL 验证 104. 判断括号字符串是否有效 105. 虚拟代理 106. 访问者模式 107. 版本号排序的方法

实现一个JSON.stringify

手写实现JSON.stringify方法,支持各种数据类型的序列化处理

问题

JSON.stringify 是 JavaScript 中用于将对象转换为 JSON 字符串的方法。需要实现一个自定义的 stringify 函数,能够正确处理各种数据类型,包括基本类型、对象、数组、特殊值等,并遵循 JSON.stringify 的转换规则。

解答

function myStringify(value, replacer = null, space = 0) {
  // 处理缩进空格
  let indent = '';
  if (typeof space === 'number' && space > 0) {
    indent = ' '.repeat(Math.min(space, 10));
  } else if (typeof space === 'string') {
    indent = space.slice(0, 10);
  }
  
  // 当前缩进级别
  let currentIndent = '';
  
  // 主序列化函数
  function serialize(val, depth = 0) {
    // 更新当前缩进
    currentIndent = indent.repeat(depth);
    const nextIndent = indent.repeat(depth + 1);
    
    // 处理 null
    if (val === null) {
      return 'null';
    }
    
    // 处理布尔值
    if (typeof val === 'boolean') {
      return String(val);
    }
    
    // 处理数字
    if (typeof val === 'number') {
      // NaN 和 Infinity 转换为 null
      return isFinite(val) ? String(val) : 'null';
    }
    
    // 处理字符串
    if (typeof val === 'string') {
      return `"${escapeString(val)}"`;
    }
    
    // 处理函数、undefined、Symbol - 在对象中会被忽略,在数组中转为 null
    if (typeof val === 'function' || typeof val === 'undefined' || typeof val === 'symbol') {
      return undefined;
    }
    
    // 处理 Date 对象
    if (val instanceof Date) {
      return `"${val.toISOString()}"`;
    }
    
    // 处理数组
    if (Array.isArray(val)) {
      const items = val.map(item => {
        const serialized = serialize(item, depth + 1);
        // undefined、函数、symbol 在数组中转为 null
        return serialized === undefined ? 'null' : serialized;
      });
      
      if (indent && items.length > 0) {
        return `[\n${nextIndent}${items.join(`,\n${nextIndent}`)}\n${currentIndent}]`;
      }
      return `[${items.join(',')}]`;
    }
    
    // 处理普通对象
    if (typeof val === 'object') {
      // 检测循环引用
      if (seen.has(val)) {
        throw new TypeError('Converting circular structure to JSON');
      }
      seen.add(val);
      
      const keys = replacer && Array.isArray(replacer) 
        ? replacer.filter(key => val.hasOwnProperty(key))
        : Object.keys(val);
      
      const pairs = [];
      for (const key of keys) {
        const value = val[key];
        const serialized = serialize(value, depth + 1);
        
        // 忽略 undefined、函数、symbol
        if (serialized !== undefined) {
          const keyStr = `"${escapeString(String(key))}"`;
          pairs.push(indent ? `${nextIndent}${keyStr}: ${serialized}` : `${keyStr}:${serialized}`);
        }
      }
      
      seen.delete(val);
      
      if (indent && pairs.length > 0) {
        return `{\n${pairs.join(',\n')}\n${currentIndent}}`;
      }
      return `{${pairs.join(',')}}`;
    }
    
    return undefined;
  }
  
  // 转义字符串中的特殊字符
  function escapeString(str) {
    const escapeMap = {
      '"': '\\"',
      '\\': '\\\\',
      '\b': '\\b',
      '\f': '\\f',
      '\n': '\\n',
      '\r': '\\r',
      '\t': '\\t'
    };
    
    return str.replace(/["\\\b\f\n\r\t]/g, char => escapeMap[char]);
  }
  
  // 用于检测循环引用
  const seen = new WeakSet();
  
  // 处理 replacer 函数
  if (typeof replacer === 'function') {
    value = replacer('', value);
  }
  
  const result = serialize(value);
  
  // 顶层的 undefined、函数、symbol 返回 undefined
  return result === undefined ? undefined : result;
}

使用示例

// 基本类型
console.log(myStringify(123)); // "123"
console.log(myStringify('hello')); // "\"hello\""
console.log(myStringify(true)); // "true"
console.log(myStringify(null)); // "null"

// 特殊值
console.log(myStringify(undefined)); // undefined
console.log(myStringify(NaN)); // "null"
console.log(myStringify(Infinity)); // "null"

// 对象
const obj = {
  name: 'John',
  age: 30,
  active: true,
  score: null
};
console.log(myStringify(obj));
// {"name":"John","age":30,"active":true,"score":null}

// 数组
const arr = [1, 'test', true, null, undefined, NaN];
console.log(myStringify(arr));
// [1,"test",true,null,null,null]

// 嵌套对象
const nested = {
  user: {
    name: 'Alice',
    hobbies: ['reading', 'coding']
  },
  count: 42
};
console.log(myStringify(nested));
// {"user":{"name":"Alice","hobbies":["reading","coding"]},"count":42}

// 使用缩进
console.log(myStringify(nested, null, 2));
// {
//   "user": {
//     "name": "Alice",
//     "hobbies": [
//       "reading",
//       "coding"
//     ]
//   },
//   "count": 42
// }

// Date 对象
console.log(myStringify(new Date('2024-01-01')));
// "2024-01-01T00:00:00.000Z"

// 忽略函数和 undefined
const withFunc = {
  name: 'test',
  fn: function() {},
  undef: undefined,
  value: 123
};
console.log(myStringify(withFunc));
// {"name":"test","value":123}

// 循环引用检测
const circular = { name: 'test' };
circular.self = circular;
try {
  myStringify(circular);
} catch (e) {
  console.log(e.message); // "Converting circular structure to JSON"
}

关键点

  • 类型判断顺序:按照 null、boolean、number、string、function/undefined/symbol、Date、Array、Object 的顺序进行判断,确保特殊类型优先处理

  • 特殊值处理:NaN 和 Infinity 转换为 null;undefined、函数、Symbol 在对象中被忽略,在数组中转为 null;顶层返回 undefined

  • 字符串转义:正确转义双引号、反斜杠、换行符等特殊字符,确保生成的 JSON 字符串合法

  • 循环引用检测:使用 WeakSet 记录已访问的对象,检测到循环引用时抛出 TypeError 异常

  • 缩进格式化:支持 space 参数,可以是数字(空格数)或字符串,实现美化输出的 JSON 格式

  • Date 对象处理:Date 对象调用 toISOString() 方法转换为 ISO 8601 格式的字符串

  • replacer 支持:支持数组形式的 replacer,用于过滤对象的键(函数形式的 replacer 可进一步扩展)

  • 递归序列化:通过递归处理嵌套的对象和数组,并正确管理缩进层级