Search code examples
javascriptjqueryjsonstringify

Convert custom javascript object to json


I am trying to convert a custom object in javascript to a json string but i keep getting a circular reference error. Is there a way to use JSON.stringify or do I have to manually create the string myself?

Here is my code:

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);

As you can see I am trying to stringify the configuration object which contains a comment (string), instances(array of instance objects), and connections (array of connection objects).

If there is a better way to do this please let me know. Thank you


Solution

  • If you don't use new when calling the function, your return this will refer to window, that is what creates the circular reference.

    This will work

    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)