還有一個類似的問題here,你 一定錯過了它。
CSV
庫解析CSV
字符串不是文件。它給你一個空的數組的原因是
是因爲它不是完整的CSV
,即至少1個頭+ 1項。
以下是源代碼中的文檔。
LINE 673
/**
* $.csv.toObjects(csv)
* Converts a CSV string to a javascript object.
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
...
**/
正如在評論中指出,處理CSV
文件作爲巨大的,在瀏覽器
是不是一個明智的決定,最好在服務器上完成的。
以下是您可以打開文件並處理內容的一種方法。
注意:它只適用於Firefox。 Three.js
庫扼流圈IE 8。它抱怨
關於語法錯誤(??)。你會得到一個Uncaught exception: DOMException: NETWORK_ERR
與歌劇。
而且,你會得到一個syntax error
在由於解析無效的(非)XML
(即在CSV
內容)的Firefox 19.0.2。
這不是最優雅的解決方案。它只是工作。
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testing CSV with jQuery csv.0.71</title>
<meta charset = "utf-8">
<script src = "./three.min.js"></script>
<script src = "./jquery-2.1.0.min.js"></script>
<script src = "./stats.min.js"></script>
<script src = "./jquery.csv-0.71.js"></script>
<script>
function openCSVFile(CSVfileName){
// create the object
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
processCSVContents(httpRequest);
}
// Send the request
httpRequest.open("POST", CSVfileName, true);
httpRequest.send(null);
}
function processCSVContents(httpRequest){
console.log("--> here");
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200)
|| (httpRequest.status == 0)){
// Analys the contents using the stats library
// and display the results
CSVContents = httpRequest.responseText;
console.log($.csv.toObjects(CSVContents));
console.log(" => Response status: " + httpRequest.status)
console.log(CSVContents);
} else {
alert(' => There was a problem with the request. '
+ httpRequest.status + httpRequest.responseText);
}
}
}
</script>
</head>
<body>
<button type="button" onclick="openCSVFile('pets.csv');">Click Me!</button>
</body>
</html>
的CSV
文件,pets.csv包含此:
name,age,weight,species
"fluffy",3,14,"cat"
"vesuvius",6,23,"fish"
"rex",5,34,"dog"
輸出:
[{
name: "fluffy",
age: "3",
weight: "14",
species: "cat"
}, {
name: "vesuvius",
age: "6",
weight: "23",
species: "fish"
}, {
name: "rex",
age: "5",
weight: "34",
species: "dog"
}]
有局部讀取文件的另一種方式,通過HTML5's File API
對於一,加載,解析和輸出在瀏覽器上創建一個22MB文件需要花費大量時間。這真的是你需要在客戶端下載和執行的東西嗎? – prabindh
http://papaparse.com/ –
jquery-csv作者在這裏。瀏覽器對內存消耗有嚴格的限制。 jquery-csv同步解析數據,所以它可能無法處理22MB的數據。如果您只是在數據上運行reduce以計算統計信息,請使用PapaParse的流處理。 –