我有一个包含循环引用的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