Javascript 在执行 JSON.stringify() 时规避错误将循环结构转换为 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5410162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:04:55  来源:igfitidea点击:

circumvent ERROR Converting circular structure to JSON when doing JSON.stringify()?

javascriptjsonserialization

提问by dr jerry

For debugging I want to serialize javascript objects with JSON.stringify(myobject). But this gives:

为了调试,我想用 JSON.stringify(myobject) 序列化 javascript 对象。但这给出了:

TypeError: Converting circular structure to JSON

Is there a way to prevent this, by for instance pruning the output tree?

有没有办法防止这种情况,例如修剪输出树?

Some more background:

更多背景:

I want to collect some data on different objects and see what is going on, and why a feature works for one situation but not for another. By comparing outputs I hope to be able to find differences which explains why it is not working in "another" situation. I'm using jquery and my debug horse is called chrome. If there are better alternatives for doing this type of debugging activities I'm also very much interested!

我想收集一些关于不同对象的数据,看看发生了什么,以及为什么一个功能适用于一种情况而不适用于另一种情况。通过比较输出,我希望能够找到差异,这解释了为什么它在“另一种”情况下不起作用。我正在使用 jquery,我的调试马被称为 chrome。如果有更好的替代方法来进行此类调试活动,我也非常感兴趣!

Cheers, jeroen.

干杯,杰伦。

采纳答案by Mike Lewis

JSON.stringify(obj) does not support circular referencing such as:

JSON.stringify(obj) 不支持循环引用,例如:

var car = {}
car.myself = car;
JSON.stringify(car);

However dojox.json.refdoes support circular referencing, if you wanted to explore another option.

但是dojox.json.ref确实支持循环引用,如果您想探索另一种选择。

However if your purposes are strictly to debug, I'd suggest using the built in browser debugger such as Chrome's, IE's or Firebug(for firefox).

但是,如果您的目的是严格调试,我建议您使用内置的浏览器调试器,例如 Chrome、IE 或 Firebug(用于 firefox)。

回答by Rob Neuhaus

You can use console.log() and the chrome javascript debug console, which will happily let you inspect your object even if it has cyclic references.

您可以使用 console.log() 和 chrome javascript 调试控制台,即使它具有循环引用,它也会很高兴地让您检查您的对象。

回答by Nathan Breit

For node.js json-refis a nice lightweight alternative to the dojox.json.ref function suggested by Mike Lewis.

对于 node.js,json-ref是 Mike Lewis 建议的 dojox.json.ref 函数的一个很好的轻量级替代方案。

回答by ajtrichards

You can now use Douglas Crockford's JSON Stringify plugin:

您现在可以使用 Douglas Crockford 的 JSON Stringify 插件:

https://github.com/douglascrockford/JSON-js

https://github.com/douglascrockford/JSON-js

This has a decycle option in the download file cycle.js. You could also use console.log()and inspect the JSON in your browsers console.

这在下载文件中有一个 decycle 选项cycle.js。您还可以console.log()在浏览器控制台中使用和检查 JSON。