将自定义 JavaScript 对象转换为 JSON

12 浏览
0 Comments

将自定义 JavaScript 对象转换为 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 = "这是一个测试评论";
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);

正如你所看到的,我正在尝试将包含评论(字符串)、实例数组和连接数组的配置对象转换为字符串。

如果有更好的方法,请告诉我。谢谢。

0
0 Comments

当调用函数时,没有使用new关键字,导致返回的this将指向window,这就创建了循环引用的问题。

解决方法是在调用函数时使用new关键字,将this正确地指向函数的实例对象。

具体解决方法如下:

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)

非常感谢。问题已解决。对于糟糕的问题,我表示抱歉...

0