2015-12-02 59 views
1

我想從下面的Json數據數組中生成一個csv。使用Javascript將Json數組轉換爲數組

var keyDistribution = [ 
         [ 
          { 
           "port": 4444, 
           "ipAddress": "52.35.15.121", 
            "noOfKeys": 1 
           }, 
           { 
            "port": 2222, 
            "ipAddress": "52.35.15.121", 
            "noOfKeys": 1 
           }, 
           { 
            "port": 3333, 
            "ipAddress": "52.35.15.121", 
            "noOfKeys": 0 
           } 
           ] 
          ]; 

我該如何做到這一點?

我知道如何從陣列生成CSV作爲初級講座:

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]]; 
     var csvContent = "data:text/csv;charset=utf-8,"; 
     keyDistribution.forEach(function(infoArray, index){ 

      dataString = infoArray.join(","); 
      csvContent += index < data.length ? dataString+ "\n" : dataString; 

     }); 
     var encodedUri = encodeURI(csvContent); 
     window.open(encodedUri); 
     var encodedUri = encodeURI(csvContent); 
     var link = document.createElement("a"); 
     link.setAttribute("href", encodedUri); 
     link.setAttribute("download", "my_data.csv"); 

     link.click(); 

可以有一個人請幫我我怎麼能生成JSON數據keyDistribution變量)數組這些數據?

我想在格式輸出:

[["port": 4444, "ipAddress": "52.35.15.121","noOfKeys": 1], ["port": 2222, "ipAddress": "52.35.15.121", "noOfKeys": 1]...]; 

編輯 我只是想在列標題的要求。 The CSV Snapshot

+0

你想要的是無效的 - 即使它的JavaScript或JSON。 –

+0

其實,沒有JSON。它只是一個數組(*的數組*)的對象,而不是數組。你可以使用'for'遍歷它的鍵並收集相同的數據。 –

+1

[安全地將JSON字符串轉換爲對象]可能的重複(http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) –

回答

1

所有你需要的是這個數組對象數組的迭代,就像這樣:

var csvContent = "data:text/csv;charset=utf-8,"; 

// Iterating through 0th index element as it contains all the objects 
keyDistribution[0].forEach(function (infoArray, index) { 

    // Fetching all keys of a single object 
    var _keys = Object.keys(infoArray); 
    var dataString = []; 

    if(index==0){ 
    [].forEach.call(_keys, function(inst, i){ 
     dataString.push(inst); 
    }); 
    dataString = dataString.join(","); 
    csvContent += index < keyDistribution[0].length ? dataString + "\n" : dataString; 
    dataString = []; 
    } 

    [].forEach.call(_keys, function(inst, i){ 
    dataString.push(infoArray[inst]); 
    }); 

    // From here the code is same. 
    dataString = dataString.join(","); 
    csvContent += index < keyDistribution[0].length ? dataString + "\n" : dataString; 

}); 
var encodedUri = encodeURI(csvContent); 
window.open(encodedUri); 
var encodedUri = encodeURI(csvContent); 
var link = document.createElement("a"); 
link.setAttribute("href", encodedUri); 
link.setAttribute("download", "my_data.csv"); 

link.click(); 
+0

嗨,無效,我得到錯誤[] .forEach.call(,函數(inst,i){說意想不到的問題「,」。任何想法是什麼問題? –

+0

對不起,我現在檢查。 – void

+0

現在我得到了「 Uncaught TypeError:infoArray.join is not an function「error。 –