2013-07-22 109 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());,它按預期工作。