博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Converting circular structure to JSON
阅读量:7080 次
发布时间:2019-06-28

本文共 1579 字,大约阅读时间需要 5 分钟。

hot3.png

TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge)

什么问题?

该 JSON 格式本身不支持对象引用(虽然存在IETF草案),因此JSON.stringify()不会尝试解决这些问题,并相应地失败。

// Demo: Circular referencevar o = {};o.o = o;// Note: cache should not be re-used by repeated calls to JSON.stringify.var cache = [];JSON.stringify(o, function(key, value) {    if (typeof value === 'object' && value !== null) {        if (cache.indexOf(value) !== -1) {            // Duplicate reference found            try {                // If this value does not reference a parent it can be deduped                return JSON.parse(JSON.stringify(value));            } catch (error) {                // discard key if value cannot be deduped                return;            }        }        // Store value in our collection        cache.push(value);    }    return value;});cache = null; // Enable garbage collection

最佳解决方案

var circularReference = {otherData: 123};circularReference.myself = circularReference;

wrong examples

JSON.stringify(circularReference);// TypeError: cyclic object value

要序列化循环引用,您可以使用支持它们的库(例如cycle.js)或自己实现解决方案,这需要通过可序列化的值查找和替换(或删除)循环引用。

const getCircularReplacer = () => {  const seen = new WeakSet();  return (key, value) => {    if (typeof value === "object" && value !== null) {      if (seen.has(value)) {        return;      }      seen.add(value);    }    return value;  };};JSON.stringify(circularReference, getCircularReplacer());

参考:

转载于:https://my.oschina.net/johnsken/blog/1936515

你可能感兴趣的文章
2012年福州中小学最新排名
查看>>
基于MSAA的自动化封装和设计—python版(转)
查看>>
cf 1B. Spreadsheets
查看>>
DSP\BIOS调试Heaps are enabled,but not set correctly
查看>>
任务超期后的定时器处理
查看>>
myeclipse乱码问题和 编码设置
查看>>
WEB打印的几种方案
查看>>
linux下安装QT过程
查看>>
ADO.NET访问SQL Server调用存储过程带回参
查看>>
为outlook增加“邮件召回”功能
查看>>
设计模式12---设计模式之代理模式(Proxy)(结构型)
查看>>
[置顶] 实现360度全景图像的利器--PanoramaGL
查看>>
杀人放火金腰带,修桥补路无尸骸。
查看>>
UVa 10012 - How Big Is It? 堆球问题 全排列+坐标模拟 数据
查看>>
【转载】pygame的斜线运动
查看>>
How to measure IOPS for VMware
查看>>
GNU风格 ARM汇编语法4
查看>>
poj2148
查看>>
jQuery实现侧边导航栏效果
查看>>
javascript使浏览器关闭前弹出确认
查看>>