これに似た質問がここにあります。見逃したに違いありません。
ライブラリは、ファイルではなく文字列を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
に、ブラウザーと同じくらい巨大なファイルを処理する
ことは賢明な決定ではなく、サーバーで行うのが最善です。
ファイルを開いて内容を処理する方法の 1 つを次に示します。
注: Firefoxでのみ機能します。ライブラリはIE 8Three.js
でチョークします。
構文エラー(??)について文句を言います。Opera
で取得できます。
Uncaught exception: DOMException: NETWORK_ERR
また、Firefox 19.0.2 では、無効 (非) (つまり、コンテンツ) を解析する
ため、syntax error
がXML
発生CSV
します。
これは最もエレガントなソリューションではありません。それだけで機能します。
<!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 の File APIを使用して、ローカルでファイルを読み取る別の方法があります。