我有一个 JavaScript 对象定义,其中包含一个循环引用:它有一个引用父对象的属性。
它还具有我不想传递到服务器的功能。我将如何序列化和反序列化这些对象?
我读过最好的方法是使用 Douglas Crockford 的 stringify。但是,我在 Chrome 中收到以下错误:
类型错误:将圆形结构转换为 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,如何在发送到服务器之前进行序列化并反序列化它?