我想從下面的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]...];
你想要的是無效的 - 即使它的JavaScript或JSON。 –
其實,沒有JSON。它只是一個數組(*的數組*)的對象,而不是數組。你可以使用'for'遍歷它的鍵並收集相同的數據。 –
[安全地將JSON字符串轉換爲對象]可能的重複(http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) –