【JS Fix】JSON.stringify 安全模式,兼容循环引用对象

该博客介绍了一个实现JSON.stringify的函数,该函数在序列化时能处理循环引用的对象。通过设置`cycleReplacer`参数,可以自定义循环引用值的序列化方式。示例展示了如何使用该函数处理包含循环引用的对象,并显示为`<circular>`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON.stringify 安全模式

/**
 *  序列化为Json字符串 (安全模式,兼容循环引用对象)
 *  @param  {*}               source    输入源
 *  @param  {Function|Array}  replacer  序列化方式 ( Function: 自定义转换,暴露参数: (<this: 当前对象> key: 键, value: 值, isCycle: 是否循环引用) | Array: 仅转换存在的key值 )
 *  @param  {Number|String}   space     指定缩进用的空白字符串 ( Number: 缩进空格数 | String: 缩进符 )
 *  @return {String}
 */
function JsonStringify(source, replacer, space) {
  let stack = [], selectKeys = Array.isArray(replacer) && replacer.map(v => typeof v == 'number' ? v.toString() : v)
  return JSON.stringify(source, function (key, value) {
    let isChild = stack.length > 0, isCycle = false
    if (isChild) {
      if (selectKeys && !selectKeys.includes(key)) return
      let thisPos = stack.indexOf(this)
      thisPos != -1 ? stack.splice(thisPos + 1) : stack.push(this)
      isCycle = stack.includes(value)
    }
    if (typeof replacer == 'function') {
      value = replacer.call(this, key, value, isCycle)
      if (isChild) isCycle = stack.includes(value)
    }
    if (isCycle) return
    if (typeof value == 'bigint') value = value.toString()
    if (!isChild) stack.push(value)
    return value
  }, space)
}
使用示例
var w = { w1: 1, w2: 2 }
var a = { a: 11, b: 22, c: [33, w, 44] }
w.w3 = a
a.d = a
a.e = w
a.c[3] = a

JsonStringify(a, null, 2)
JsonStringify(a, (key, value, isCycle) => isCycle ? '<circular>' : value, 2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值