-2

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

2
  • 1
    you should first start by creating object instances, with the new keyword Commented Mar 25, 2016 at 15:51
  • Note that the JSON created from custom objects does not preserve the object subtypes. When you parse it you'll get plain objects. JSON doesn't have any way to represent custom object types. Commented Mar 25, 2016 at 15:59

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. That solved it. Sorry for the bad question...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.