开发者

jQuery CSV plugin won't split rows into arrays-of-arrays

开发者 https://www.devze.com 2023-01-07 07:45 出处:网络
I am trying to use the jQuery \"CSV\" plugin, as documented here: http://code.google.com/p/js-tables/wiki/CSV

I am trying to use the jQuery "CSV" plugin, as documented here: http://code.google.com/p/js-tables/wiki/CSV

According to the documentation:

// Convert CSV data into array of arrays
jQuery.csv()("1,2,3\n4,5,6\n7,8,9\n"); // = [ [1,2,3], [4,5,6], [7,8,9] ]

But when I attempt to do something similar, it just seems to treat the "\n" as another character in the middle of an array element.

What am I doing wrong? I am using jQuery 1.4.2 and Firefox 3.5.10 for testing. I have also tried it with jQuery 1.3 and get the same result.

If it is a problem with the plugin, then can someone suggest another plugin for reading CSV? My ultimate goal is to convert CSV from a string into an HTML table; the only plugin I can find that specifically does this requires the CSV to come from a file, which is not desirable for my task.

Here is a minimal test page I put together which illustrates that it's not separating the lines into sub-arrays:

<html>
<head>
  <title>CSVtest</title>
  <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
  <script type="text/javascript" src="jquery.csv.js"></s开发者_如何学编程cript>
  <script type="text/javascript">
     $(document).ready(function() {
      var lines = $.csv()("a,b\nc,d");
      alert(lines[0][1]); // Displays: b 
                          //           c instead of the expected b
     });
  </script>
</head>
<body>
</body>
</html>


Make sure you're using the latest version of the plugin. I copied and pasted your example using jQuery 1.4.2 and the (now outdated) CSV plugin from http://js-tables.googlecode.com/svn/trunk/jquery.csv.min.js and it works fine.

http://jsfiddle.net/KRzzF/

Tested in IE8, IE6, Google Chrome and Firefox. I also tested

alert(lines[1][1]);

and sure enough, the alert displayed "d".


If you only deal with simple data (no quotation) you can do something like this:

function csv(text) {
  var lines = text.split("\n");
  for ( var i = 0; i < lines.length; i++ ) {
    if (!lines[i])
      lines.splice(i, 1);
    else 
      lines[i] = lines[i].split(",");
  }
  return lines;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消