JSON.stringify()循环引用问题

const o = {
  a: 1,
  b: 2
}
o.self = o
JSON.stringify(o) // Uncaught TypeError: Converting circular structure to JSON
const o = {
  a: 1,
  b: 2
}
o.self = o

function stringify(o) {
  const cached = new WeakSet()
  const replacer = (key, value) => {
    return (key, value) => {
      if (typeof value === 'object' && value !== null) {
        if (cached.has(value)) {
          return
        }
        cached.add(value)
      }
      return value
    }
  }
  return JSON.stringify(o, replacer)
}
stringify(o)  // '{"a":1,"b":2}'

主要是利用到JSON.stringifyopen in new window的第二个参数replacer。使用WeakSet是为了防止内存泄漏,也可以换成数组,但是用数组的话,最后要把数组设为null,以便GC回收垃圾。

function stringify(o) {
  let cached = []
  const replacer = (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (cached.includes(value)) {
        return
      }
      cached.push(value)
    }
    return value
  }
  const res = JSON.stringify(o, replacer)
  cached = null
  return res
}
stringify(o)
Last Updated: