2013-07-22 112 views
0

我有一个JSON如下阅读JSON创建一个逗号分隔值:如何使用节点JS

{ 
    "workloadId": "68cf9344-5a3c-4e4a-927c-c1c9b6e48ccc", 
    "elements": [ 
     { 
      "name": "element1", 
      "uri": "vm/hpcloud/nova/large" 
     }, 
     { 
      "name": "element2", 
      "uri": "vm/hpcloud/nova/small" 
     } 
    ], 
    "workloadStatus": "none" 
} 

我需要得到逗号分隔字符串如下: 部件1,element2的

时我试着给出如下,我得到空字符串:

app.post('/pricingdetails', function(req, res) { 

    var workload = req.body; 

    var arr = new Array(); 
    for(var index in workload.elements) 
    { 
     arr[index] = workload.elements[index].uri; 
    } 
    console.log(arr.join(",")); 
} 
+0

你可以在循环中的每一行之后使用console.log arr [index]。第一眼看起来似乎不错,除了工作负载不是json对象,而是字符串本身? –

+0

将上面列出的JSON直接分配给工作负载按预期工作。看起来错误可能在作业中。请尝试将响应分配给工作负载,而不是工作负载=请求身份。 – dc5

回答

1

元素是一个数组。切勿使用for/in作为数组。使用标准的for循环,而不是:

for(var i = 0; i < workload.elements.length; ++i) { 
    arr.push(workload.elements[i].uri); 
} 
console.log(arr.join(',')); 
0

节点将让你使用forEach方法,而不是for环或for/in(其中有潜力cause problems后者)。 避免new Array()another Crockford-ism,但我也只是发现[]符号更简洁和可读。

var workload = req.body; 

var arr = []; 

workload.elements.forEach(function(el) { 
    arr.push(el.uri); 
}); 

console.log(arr.join(',')); 

这些排序挑剔的一边,就像DC5我尝试了定义您的JSON一个变量,你的代码做了我所期待的(返回一个逗号加入数组元素)。你用什么来调用这条路线,以及如何将它传递给指定的JSON?

编辑:使用

curl -v -H "Content-type: application/json" -X POST -d '{"workloadId": "68cf9344-5a3c-4e4a-927c-c1c9b6e48ccc", "elements": [{"name": "element1", "uri": "vm/hpcloud/nova/large"}, {"name": "element2", "uri": "vm/hpcloud/nova/small"} ], "workloadStatus": "none"}' http://localhost:3000/pricingdetails 

如果不使用bodyParser()我失败。在我的代码中使用app.use(express.bodyParser());,它按预期工作。