JSON.stringify出現 "Converting circular structure to JSON"


JSON.stringify()  我們很熟悉了,將一個對象轉換為json形式的字符串. 

但是如果你在瀏覽器控制台中輸出 JSON.stringify(window). 如果期望輸出一段文字, 可能會失望了. 事實上, 會輸出結果如下:

 

錯誤信息很明顯了, 對象中有循環引用. 解決方案如下:

參考鏈接:http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json

// Demo: Circular reference
var 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) {
            // Circular reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

JSON.stringify說明  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

 

至於出現循環引用的原因,參考如下:

原文鏈接:

http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM