将自定义 javascript 对象转换为 json
Convert custom javascript object to json
我正在尝试将 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
,您的 return this
将引用 window
,这就是创建循环引用的原因。
这会起作用
connections.push(new connection(new from("34hvd","inputs", 0), new to("dheb3", "outputs", 0)));
instances.push(new instance("34vd", "tee"));
instances.push(new instance("dheb2", "average"));
var config = new configuration(comments, instances, connections);
console.log(config)
我正在尝试将 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
,您的 return this
将引用 window
,这就是创建循环引用的原因。
这会起作用
connections.push(new connection(new from("34hvd","inputs", 0), new to("dheb3", "outputs", 0)));
instances.push(new instance("34vd", "tee"));
instances.push(new instance("dheb2", "average"));
var config = new configuration(comments, instances, connections);
console.log(config)