将循环结构转换为 JSON——有什么方法可以找到它抱怨的字段吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7005205/
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
Converting circular structure to JSON -- Any way to find what field it is complaining about?
提问by Mike
I'm trying to stringify(...) an object in Chrome, and I keep getting a "Converting circular structure to JSON" message, despite the fact that (as far as I know) no such structure exists.
我正在尝试对 Chrome 中的对象进行字符串化(...),尽管事实上(据我所知)不存在这样的结构,但我不断收到“将循环结构转换为 JSON”的消息。
I've been over the code a dozen times and can't find any circular references whatsoever. Is there any way to get Chrome to tell me what it's bitching about beyond this painfully useless error message?
我已经检查了十几次代码,但找不到任何循环引用。除了这个令人痛苦的无用错误消息之外,有什么方法可以让 Chrome 告诉我它在抱怨什么?
采纳答案by Paul
Pardon me if this is too obvious. At the time of writing, I dont know what you have tried.
如果这太明显了,请原谅我。在撰写本文时,我不知道您尝试过什么。
insert
插入
console.log(the object);
replacing 'the object' with the object you are passing to JSON.stringify()
用您要传递给的对象替换“对象” JSON.stringify()
insert this line before the JSON.stringifycall
在JSON.stringify调用之前插入这一行
and look in the console log (shift control J) for the object. In the console log the object will be tagged with a ">" symbol which can be clicked to expand to the fields.
并在控制台日志(移位控制 J)中查找该对象。在控制台日志中,对象将被标记为“>”符号,单击该符号可以展开到字段。
It is complaining about an object that has pointers into itself, like this kind of object:
它抱怨一个具有指向自身的指针的对象,例如这种对象:
A = [];
A[0] = A;
JSON.stringify(A); // circular error
回答by user2683246
You can use dojox.json.refto find circular references. This code prints json representation of your objectWithCircularReferences:
您可以使用dojox.json.ref来查找循环引用。此代码打印您的 json 表示objectWithCircularReferences:
require(["dojox/json/ref"], function(){
console.log(dojox.json.ref.toJson(objectWithCircularReferences));
});
Any occurence of "$ref" substring in its output to console will help you locate circular references. You can alternatively pipe this json output to global variable ZZZ like this if you wish:
控制台输出中出现的任何“$ref”子字符串都将帮助您找到循环引用。如果您愿意,您也可以像这样将此 json 输出通过管道传输到全局变量 ZZZ:
require(["dojox/json/ref"], function(){
window.ZZZ = dojox.json.ref.toJson(objectWithCircularReferences);
});
And of course you need to include dojo library beforehand. In an html file:
当然,您需要事先包含 dojo 库。在一个 html 文件中:
<script src="//yandex.st/dojo/1.9.1/dojo/dojo.js"></script>
In firebug console:
在萤火虫控制台中:
include("//yandex.st/dojo/1.9.1/dojo/dojo.js")
In Chrome console:
在 Chrome 控制台中:
SCRIPT = document.createElement('script');
SCRIPT.src = '//yandex.st/dojo/1.9.1/dojo/dojo.js';
document.body.appendChild(SCRIPT);

