【发布时间】:2016-07-13 09:34:58
【问题描述】:
我正在尝试将 javascript 中的自定义对象转换为 json 字符串,但我不断收到循环引用错误。有没有办法使用 JSON.stringify 还是我必须自己手动创建字符串?
这是我的代码:
function configuration(comments, instances, connections)
{
this.comments = comments;
this.instances = instances;
this.connections = connections;
return this;
}
function instance(id, type)
{
this.id = id;
this.type = type;
return this;
}
function connection(from, to)
{
this.from = from;
this.to = to;
return this;
}
function from(id, property, index)
{
this.id = id;
this.property = property;
this.index = index;
return this;
}
function to(id, property, index)
{
this.id = id;
this.property = property;
this.index = index;
return this;
}
var comments = "this is a test comment";
var instances = [];
var connections = [];
connections.push(connection(from("34hvd","inputs", 0), to("dheb3", "outputs", 0)));
instances.push(instance("34vd", "tee"));
instances.push(instance("dheb2", "average"));
var config = configuration(comments, instances, connections);
JSON.stringify(config);
如您所见,我正在尝试对包含注释(字符串)、实例(实例对象数组)和连接(连接对象数组)的配置对象进行字符串化。
如果有更好的方法,请告诉我。谢谢
【问题讨论】:
-
您应该首先使用
new关键字创建对象实例 -
请注意,从自定义对象创建的 JSON 不保留对象子类型。当你解析它时,你会得到普通的对象。 JSON 没有任何方式来表示自定义对象类型。
标签: javascript jquery json stringify