循環参照を含むJavaScriptオブジェクト定義があります。これには、親オブジェクトを参照するプロパティがあります。
また、サーバーに渡したくない機能もあります。これらのオブジェクトをどのようにシリアル化および逆シリアル化しますか?
これを行うための最良の方法は、ダグラス・クロックフォードの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));
}
}
これは、この質問のために作成したテストケースです。このコード内にエラーがありますが、基本的にオブジェクト内にオブジェクトがあり、オブジェクトが作成されたときに親オブジェクトが何であるかを示すために各オブジェクトに参照が渡されます。各オブジェクトには、文字列化したくない関数も含まれています。などのプロパティが必要ですPerson.Name
。
サーバーに送信する前にシリアル化して、同じJSONが返されると仮定して逆シリアル化するにはどうすればよいですか?