Chrome 发送请求出错:TypeError: 将循环结构转换为 JSON。
Chrome 发送请求出错:TypeError: 将循环结构转换为 JSON。
我遇到了以下问题...
chrome.extension.sendRequest({ req: "getDocument", docu: pagedoc, name: 'name' }, function(response){ var efjs = response.reply; });
调用了以下内容...
case "getBrowserForDocumentAttribute": alert("ZOMG HERE"); sendResponse({ reply: getBrowserForDocumentAttribute(request.docu,request.name) }); break;
然而,我的代码从来没有到达过“ZOMG HERE”,而是在运行chrome.extension.sendRequest
时抛出以下错误
Uncaught TypeError: Converting circular structure to JSON chromeHidden.JSON.stringify chrome.Port.postMessage chrome.initExtension.chrome.extension.sendRequest suggestQuery
有何人知道是什么原因造成的吗?
admin 更改状态以发布 2023年5月21日
根据Mozilla上的JSON文档,JSON.stringify
有第二个参数replacer
,可以在解析树时用来过滤/忽略子项。然而,在Node.js中,我们无法避免循环引用。所以我们可以像这样做:
function censor(censor) { var i = 0; return function(key, value) { if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) return '[Circular]'; if(i >= 29) // seems to be a harded maximum of 30 serialized objects? return '[Unknown]'; ++i; // so we know we aren't using the original object anymore return value; } } var b = {foo: {bar: null}}; b.foo.bar = b; console.log("Censoring: ", b); console.log("Result: ", JSON.stringify(b, censor(b)));
结果是:
Censoring: { foo: { bar: [Circular] } } Result: {"foo":{"bar":"[Circular]"}}
不幸的是,在循环引用之前似乎有30次迭代的最大限制。否则,这个方法是可以工作的。我甚至从这里使用了areEquivalent
,但是在30次迭代后,JSON.stringify
仍然会抛出异常。但是,如果你真的需要,在顶层对象上,它足够好地描述了这个对象。也许有人可以改进这个方法?在Node.js中为HTTP请求对象,我得到了:
{ "limit": null, "size": 0, "chunks": [], "writable": true, "readable": false, "_events": { "pipe": [null, null], "error": [null] }, "before": [null], "after": [], "response": { "output": [], "outputEncodings": [], "writable": true, "_last": false, "chunkedEncoding": false, "shouldKeepAlive": true, "useChunkedEncodingByDefault": true, "_hasBody": true, "_trailer": "", "finished": false, "socket": { "_handle": { "writeQueueSize": 0, "socket": "[Unknown]", "onread": "[Unknown]" }, "_pendingWriteReqs": "[Unknown]", "_flags": "[Unknown]", "_connectQueueSize": "[Unknown]", "destroyed": "[Unknown]", "bytesRead": "[Unknown]", "bytesWritten": "[Unknown]", "allowHalfOpen": "[Unknown]", "writable": "[Unknown]", "readable": "[Unknown]", "server": "[Unknown]", "ondrain": "[Unknown]", "_idleTimeout": "[Unknown]", "_idleNext": "[Unknown]", "_idlePrev": "[Unknown]", "_idleStart": "[Unknown]", "_events": "[Unknown]", "ondata": "[Unknown]", "onend": "[Unknown]", "_httpMessage": "[Unknown]" }, "connection": "[Unknown]", "_events": "[Unknown]", "_headers": "[Unknown]", "_headerNames": "[Unknown]", "_pipeCount": "[Unknown]" }, "headers": "[Unknown]", "target": "[Unknown]", "_pipeCount": "[Unknown]", "method": "[Unknown]", "url": "[Unknown]", "query": "[Unknown]", "ended": "[Unknown]" }
我创建了一个小的Node.js模块来实现这个功能:https://github.com/ericmuyser/stringy。欢迎大家改进/贡献!