1

I have an object like this:

function Point(x,y)
{
    this.coorX = x;
    this.coorY = y;
}

function Node(id,x,y)
{
    this.id = id;
    this.point = new Point(x,y);

    this.getDescription = function(){
         return this.id + ': (' + this.punto.coorX + ', ' +  this.punto.coorY + ')';
    }

}

I export a list of node in json format with:

 JSON.stringify(NodeList);

json:

 {"NodeList":[{"id":0,"point":{"coorX":15,"coorY":15},"$$hashKey":"004"},{"id":1,"point":{"coorX":15,"coorY":151},"$$hashKey":"009"},{"id":2,"point":{"coorX":25,"coorY":15},"$$hashKey":"00E"}]}

After if I import the same json with:

 NodeList = JSON.parse(text);

After the import how can I use the Node function getDescription()?

0

3 Answers 3

1

You can recreate your nodes, like so:

var items = NodeList.NodeList,
    nodes = [];

for(var i = 0; i < items.lenght; i++) {
    var item = items[i],
        point = item.point,
        node = new Node(item.id, point.coorX, point.coorY);

    nodes.push(node);
}

// call getDescription of first node
nodes[0].getDescription();
Sign up to request clarification or add additional context in comments.

Comments

0

JSON is not a programming language. It supports data as opposed to methods.

1 Comment

0

I've created a GitHub-Gist that does exactly this: https://gist.github.com/Hoff97/7518680

Use jsonWF,objWF for de and encoding.

I've got another Gist that does the same thing more efficiently and is also able to convert cyclic objects: https://gist.github.com/Hoff97/9842228

4 Comments

Link-only answers are discouraged. Please explain your approach. It seems interesting enough.
Ok, so the jsonWF function actually replaces all methods by properties that contain the actual method code. When converting the JSON-string back to an object, all properties containing method code are converted back to methods.
Um, there seems to be recursion and meta-programing involved (I'm not a fan of either). I'm sure you would get quite a few rep points if you took the time to explain the recursive process of inflating the methods/functions with assignFuncFromStr. I'd gladly vote your answer up if you explained some of the drawbacks with this approach as well as give some examples of where such a solution is reasonable to use.
Actually i would recommend using my second approach, because its cleaner and does the same thing way faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.