Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用现有方法将json转换为javascript对象?_Javascript_Json - Fatal编程技术网

如何使用现有方法将json转换为javascript对象?

如何使用现有方法将json转换为javascript对象?,javascript,json,Javascript,Json,我有一个这样的物体: 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 + ', ' +

我有一个这样的物体:

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 + ')';
    }

}
我导出json格式的节点列表,其中包含:

 JSON.stringify(NodeList);
json:

如果我导入了相同的json,那么:

 NodeList = JSON.parse(text);

导入后,如何使用
节点
函数
getDescription()

JSON不是一种编程语言。它支持数据而不是方法。

我创建了一个GitHub Gist,它正好做到了这一点:

使用jsonWF、objWF进行de和编码


我还有另一个要点,可以更有效地完成同样的事情,还可以转换循环对象:

您可以重新创建节点,如下所示:

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();
var items=NodeList.NodeList,
节点=[];
对于(变量i=0;i
不鼓励仅链接答案。请解释你的方法。这似乎很有趣。好的,所以jsonWF函数实际上用包含实际方法代码的属性替换了所有方法。当将JSON字符串转换回一个对象时,所有包含方法代码的属性都会转换回方法。嗯,似乎涉及到递归和元编程(我不喜欢这两种方法)。如果您花时间解释使用assignFuncFromStr膨胀方法/函数的递归过程,我相信您会得到相当多的代表点。如果你解释了这种方法的一些缺点,并举例说明这种解决方案在哪些方面是合理的,我很乐意投票支持你的答案。事实上,我建议使用我的第二种方法,因为它更干净,做同样的事情更快。
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();