我有一個包含循環引用的JavaScript對象定義:它有一個引用父對象的屬性。將帶有循環引用的JavaScript對象Stringify(轉換爲JSON)
它還具有我不想傳遞給服務器的功能。我將如何序列化和反序列化這些對象?
我讀過這樣做的最好方法就是使用Douglas Crockford的stringify。但是,我得到的Chrome以下錯誤:
TypeError: Converting circular structure to 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));
}
}
這是我對這個問題,創建了一個測試案例。這段代碼中存在錯誤,但本質上我有對象內的對象,並且引用傳遞給每個對象以顯示對象創建時父對象的內容。每個對象還包含函數,我不希望字符串化。我只想要諸如Person.Name
之類的屬性。
如何在發送到服務器之前序列化並反序列化它,假設返回相同的JSON?
嗨,謝謝你的回答。我應該說我正在使用jquery作爲我的庫。我當時並不認爲這是相關的,我更新了我的文章。 – user1012500
@ user1012500 - Dojo與jQuery一起工作良好。我經常包含其他庫或框架來彌補我的主要框架中的缺陷。你甚至可以提取'toJson'和'fromJson'方法並在它們周圍創建你自己的jQuery包裝器。這樣你就不需要拉動整個框架。不幸的是,jQuery沒有開箱即用,JSON.stringify無法處理這些類型的對象。所以除了上面的例子,你可能必須自己編寫這個功能。 –
嗨布蘭登,我很猶豫要添加另一個庫來解決這個問題,因爲它增加了另一個足跡。但是,我給了道場一槍,並試圖用你的例子對付我的例子。然而,我遇到了循環引用問題(我沒有太多的dojo知識,所以我只是嘗試了一些東西,但主要基於你的例子):http://jsfiddle.net/Af3d6/1/ – user1012500