将自定义javascript对象转换为json

时间:2016-03-25 15:45:41

标签: javascript jquery json stringify

我正在尝试将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);

正如您所看到的,我正在尝试对包含注释(字符串),实例(实例对象数组)和连接(连接对象数组)的配置对象进行字符串化。

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

1 个答案:

答案 0 :(得分:3)

如果您在调用该函数时未使用new,则返回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)