我有一個包含循環(huán)引用的JavaScript對象定義:它具有引用父對象的屬性。它還具有一些我不想傳遞給服務器的功能。我將如何序列化和反序列化這些對象?我讀過,做到這一點的最佳方法是使用道格拉斯·克羅克福德(Douglas Crockford)的stringify。但是,我在Chrome中遇到以下錯誤:TypeError:將圓形結構轉換為JSON編碼:function finger(xid, xparent){ this.id = xid; this.xparent; //other attributes}function arm(xid, xparent){ this.id = xid; this.parent = xparent; this.fingers = []; //other attributes this.moveArm = function() { //moveArm function details - not included in this testcase alert("moveArm Executed"); }} function person(xid, xparent, xname){ this.id = xid; this.parent = xparent; this.name = xname this.arms = [] this.createArms = function () { this.arms[this.arms.length] = new arm(this.id, this); }}function group(xid, xparent){ this.id = xid; this.parent = xparent; this.people = []; that = this; this.createPerson = function () { this.people[this.people.length] = new person(this.people.length, this, "someName"); //other commands } this.saveGroup = function () { alert(JSON.stringify(that.people)); }}這是我為這個問題創(chuàng)建的測試用例。這段代碼中有錯誤,但是本質上我在對象中有對象,并且傳遞給每個對象的引用顯示了創(chuàng)建對象時父對象是什么。每個對象還包含函數,我不想對其進行字符串化。我只想要諸如的屬性Person.Name。如果發(fā)送回相同的JSON,如何在發(fā)送到服務器之前進行序列化和反序列化?
使用循環(huán)引用對JavaScript對象進行Stringify(轉換為JSON)
慕后森
2019-10-09 15:39:15