我有以下...
1chrome.extension.sendRequest({ 2 req: "getDocument", 3 docu: pagedoc, 4 name: 'name' 5}, function(response){ 6 var efjs = response.reply; 7});
该调用以下。
1case "getBrowserForDocumentAttribute": 2 alert("ZOMG HERE"); 3 sendResponse({ 4 reply: getBrowserForDocumentAttribute(request.docu,request.name) 5 }); 6 break;
但是,我的代码永远不会到达“ ZOMG HERE”,而是在运行chrome.extension.sendRequest抛出以下错误
1 Uncaught TypeError: Converting circular structure to JSON 2 chromeHidden.JSON.stringify 3 chrome.Port.postMessage 4 chrome.initExtension.chrome.extension.sendRequest 5 suggestQuery
有谁知道是什么原因造成的?
#1楼
一种方法是从主要对象中剥离对象和功能。 并简化表格
1function simpleStringify (object){ 2 var simpleObject = {}; 3 for (var prop in object ){ 4 if (!object.hasOwnProperty(prop)){ 5 continue; 6 } 7 if (typeof(object[prop]) == 'object'){ 8 continue; 9 } 10 if (typeof(object[prop]) == 'function'){ 11 continue; 12 } 13 simpleObject[prop] = object[prop]; 14 } 15 return JSON.stringify(simpleObject); // returns cleaned up JSON 16};
#2楼
我像这样在NodeJS上解决了这个问题:
1var util = require('util'); 2 3// Our circular object 4var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}}; 5obj.foo.bar = obj; 6 7// Generate almost valid JS object definition code (typeof string) 8var str = util.inspect(b, {depth: null}); 9 10// Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case) 11str = str 12 .replace(/<Buffer[ \w\.]+>/ig, '"buffer"') 13 .replace(/\[Function]/ig, 'function(){}') 14 .replace(/\[Circular]/ig, '"Circular"') 15 .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},') 16 .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}') 17 .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),') 18 .replace(/(\S+): ,/ig, '$1: null,'); 19 20// Create function to eval stringifyed code 21var foo = new Function('return ' + str + ';'); 22 23// And have fun 24console.log(JSON.stringify(foo(), null, 4));
#3楼
这可能不是相关的答案,但是此链接检测并修复JavaScript中的循环引用可能有助于检测导致循环依赖性的对象 。
#4楼
我通常使用circular-json npm包来解决此问题。
1// Felix Kling's example 2var a = {}; 3a.b = a; 4// load circular-json module 5var CircularJSON = require('circular-json'); 6console.log(CircularJSON.stringify(a)); 7//result 8{"b":"~"}
注意:circular-json已被弃用,我现在使用flatted(来自CircularJSON的创建者):
1// ESM 2import {parse, stringify} from 'flatted/esm'; 3 4// CJS 5const {parse, stringify} = require('flatted/cjs'); 6 7const a = [{}]; 8a[0].a = a; 9a.push(a); 10 11stringify(a); // [["1","0"],{"a":"0"}]
来自: https : //www.npmjs.com/package/flatted
#5楼
我在使用jQuery formvaliadator时遇到了同样的错误,但是当我在success:函数中删除console.log时,它起作用了。