在運行nodejs程序的時候報出以下的錯誤:
2017-11-20 17:44 +08:00: TypeError: Converting circular structure to JSON
at Object.stringify (native)
at stringify (/home/dev/backend/backcode/owner-backend/node_modules/express/lib/response.js:1075:12)
at ServerResponse.json (/home/dev/backend/backcode/owner-backend/node_modules/express/lib/response.js:249:14)
at /home/ubuntu/sample/index.js:728:10
at propagateAslWrapper (/usr/lib/node_modules/pm2/node_modules/async-listener/index.js:421:23)
at /usr/lib/node_modules/pm2/node_modules/async-listener/index.js:458:70
錯誤說明指的是對象存在循環引用,在將對象進行json序列化的時候就會報錯。出現該問題的原因是在編寫代碼的時候沒有注意到javascript的語法特性,或者說語法缺陷,也就是缺少塊級作用域。
var obj = {a:1, b:2};
var s = [];
var list = ['a','b', 'c','d'];
list.forEach(function(ele, i){
var obj = {};
obj[ele] = i;
s.push(obj);
});
obj.list = s;
JSON.stringify(obj)