Javascript 将csv数据转换为数组格式

Javascript 将csv数据转换为数组格式,javascript,jquery,html,json,Javascript,Jquery,Html,Json,我正在尝试使用jquery构建wordCloud。我有一个csv文件要读取,并使用该数据形成wordCloud。 我的csv文件中有冒号 text weight Lorem 15 Ipsum 9 等等 但是输入数据需要采用以下格式 var word_array = [ {text: "Lorem", weight: 15}, {text: "Ipsum", weight: 9}, {text: "Dolor", weight: 6}

我正在尝试使用jquery构建wordCloud。我有一个csv文件要读取,并使用该数据形成wordCloud。 我的csv文件中有冒号

text weight
Lorem 15
Ipsum 9 
等等 但是输入数据需要采用以下格式

var word_array = [
          {text: "Lorem", weight: 15},
          {text: "Ipsum", weight: 9},
          {text: "Dolor", weight: 6},
          {text: "Sit", weight: 7}
          ];

我应该如何将我的csv数据转换成上述格式以形成word cloud。如果可能,请附上代码。我在我的html页面中完成了所有这些。谢谢。

您可以使用下面的代码将数据从CSV获取到数组

 /**
 * Convert data in CSV (comma separated value) format to a javascript array.
 *
 * Values are separated by a comma, or by a custom one character delimeter.
 * Rows are separated by a new-line character.
 *
 * Leading and trailing spaces and tabs are ignored.
 * Values may optionally be enclosed by double quotes.
 * Values containing a special character (comma's, double-quotes, or new-lines)
 *   must be enclosed by double-quotes.
 * Embedded double-quotes must be represented by a pair of consecutive 
 * double-quotes.
 *
 * Example usage:
 *   var csv = '"x", "y", "z"\n12.3, 2.3, 8.7\n4.5, 1.2, -5.6\n';
 *   var array = csv2array(csv);
 *  
 * Author: Jos de Jong, 2010
 * 
 * @param {string} data      The data in CSV format.
 * @param {string} delimeter [optional] a custom delimeter. Comma ',' by default
 *                           The Delimeter must be a single character.
 * @return {Array} array     A two dimensional array containing the data
 * @throw {String} error     The method throws an error when there is an
 *                           error in the provided data.
 */ 
function csv2array(data, delimeter) {
  // Retrieve the delimeter
  if (delimeter == undefined) 
    delimeter = ',';
  if (delimeter && delimeter.length > 1)
    delimeter = ',';

  // initialize variables
  var newline = '\n';
  var eof = '';
  var i = 0;
  var c = data.charAt(i);
  var row = 0;
  var col = 0;
  var array = new Array();

  while (c != eof) {
    // skip whitespaces
    while (c == ' ' || c == '\t' || c == '\r') {
      c = data.charAt(++i); // read next char
    }

    // get value
    var value = "";
    if (c == '\"') {
      // value enclosed by double-quotes
      c = data.charAt(++i);

      do {
        if (c != '\"') {
          // read a regular character and go to the next character
          value += c;
          c = data.charAt(++i);
        }

        if (c == '\"') {
          // check for escaped double-quote
          var cnext = data.charAt(i+1);
          if (cnext == '\"') {
            // this is an escaped double-quote. 
            // Add a double-quote to the value, and move two characters ahead.
            value += '\"';
            i += 2;
            c = data.charAt(i);
          }
        }
      }
      while (c != eof && c != '\"');

      if (c == eof) {
        throw "Unexpected end of data, double-quote expected";
      }

      c = data.charAt(++i);
    }
    else {
      // value without quotes
      while (c != eof && c != delimeter && c!= newline && c != ' ' && c != '\t' && c != '\r') {
        value += c;
        c = data.charAt(++i);
      }
    }

    // add the value to the array
    if (array.length <= row) 
      array.push(new Array());
    array[row].push(value);

    // skip whitespaces
    while (c == ' ' || c == '\t' || c == '\r') {
      c = data.charAt(++i);
    }

    // go to the next row or column
    if (c == delimeter) {
      // to the next column
      col++;
    }
    else if (c == newline) {
      // to the next row
      col = 0;
      row++;
    }
    else if (c != eof) {
      // unexpected character
      throw "Delimiter expected after character " + i;
    }

    // go to the next character
    c = data.charAt(++i);
  }  

  return array;
}
/**
*将CSV(逗号分隔值)格式的数据转换为javascript数组。
*
*值由逗号分隔,或由自定义的单字符分隔符分隔。
*行由新行字符分隔。
*
*将忽略前导空格和尾随空格以及制表符。
*值可以选择用双引号括起来。
*包含特殊字符(逗号、双引号或新行)的值
*必须用双引号括起来。
*嵌入的双引号必须由一对连续的
*双引号。
*
*用法示例:
*var csv='“x”,“y”,“z”\n12.3,2.3,8.7\n4.5,1.2,-5.6\n';
*var阵列=CSV2阵列(csv);
*  
*作者:何塞·德容,2010年
* 
*@param{string}data以CSV格式显示数据。
*@param{string}delimeter[可选]自定义delimeter。默认情况下,逗号为“”
*Delimeter必须是单个字符。
*@return{Array}Array包含数据的二维数组
*@throw{String}error当出现错误时,该方法会抛出错误
*提供的数据中存在错误。
*/ 
功能csv2array(数据、测力计){
//取回delimeter
如果(delimeter==未定义)
delimeter=',';
如果(delimeter和delimeter.length>1)
delimeter=',';
//初始化变量
变量换行符='\n';
var eof=“”;
var i=0;
var c=数据特征(i);
var行=0;
var-col=0;
var数组=新数组();
而(c!=eof){
//跳过空白
而(c=''| | c='\t'| | c='\r'){
c=data.charAt(++i);//读取下一个字符
}
//获得价值
var值=”;
如果(c=='\'){
//用双引号括起来的值
c=数据字符(++i);
做{
如果(c!=“\”){
//读取一个常规字符并转到下一个字符
值+=c;
c=数据字符(++i);
}
如果(c=='\'){
//检查转义的双引号
var cnext=data.charAt(i+1);
如果(cnext=='\''){
//这是一个转义的双引号。
//在值中添加双引号,并向前移动两个字符。
值+=“\”;
i+=2;
c=数据字符(i);
}
}
}
而(c!=eof&&c!='\'');
如果(c==eof){
抛出“数据意外结束,需要双引号”;
}
c=数据字符(++i);
}
否则{
//不带引号的值
而(c!=eof&&c!=delimeter&&c!=newline&&c!=''&&c!='\t'&&c!='\r'){
值+=c;
c=数据字符(++i);
}
}
//将值添加到数组中

如果(array.length您可以使用下面的代码从CSV到阵列获取数据

 /**
 * Convert data in CSV (comma separated value) format to a javascript array.
 *
 * Values are separated by a comma, or by a custom one character delimeter.
 * Rows are separated by a new-line character.
 *
 * Leading and trailing spaces and tabs are ignored.
 * Values may optionally be enclosed by double quotes.
 * Values containing a special character (comma's, double-quotes, or new-lines)
 *   must be enclosed by double-quotes.
 * Embedded double-quotes must be represented by a pair of consecutive 
 * double-quotes.
 *
 * Example usage:
 *   var csv = '"x", "y", "z"\n12.3, 2.3, 8.7\n4.5, 1.2, -5.6\n';
 *   var array = csv2array(csv);
 *  
 * Author: Jos de Jong, 2010
 * 
 * @param {string} data      The data in CSV format.
 * @param {string} delimeter [optional] a custom delimeter. Comma ',' by default
 *                           The Delimeter must be a single character.
 * @return {Array} array     A two dimensional array containing the data
 * @throw {String} error     The method throws an error when there is an
 *                           error in the provided data.
 */ 
function csv2array(data, delimeter) {
  // Retrieve the delimeter
  if (delimeter == undefined) 
    delimeter = ',';
  if (delimeter && delimeter.length > 1)
    delimeter = ',';

  // initialize variables
  var newline = '\n';
  var eof = '';
  var i = 0;
  var c = data.charAt(i);
  var row = 0;
  var col = 0;
  var array = new Array();

  while (c != eof) {
    // skip whitespaces
    while (c == ' ' || c == '\t' || c == '\r') {
      c = data.charAt(++i); // read next char
    }

    // get value
    var value = "";
    if (c == '\"') {
      // value enclosed by double-quotes
      c = data.charAt(++i);

      do {
        if (c != '\"') {
          // read a regular character and go to the next character
          value += c;
          c = data.charAt(++i);
        }

        if (c == '\"') {
          // check for escaped double-quote
          var cnext = data.charAt(i+1);
          if (cnext == '\"') {
            // this is an escaped double-quote. 
            // Add a double-quote to the value, and move two characters ahead.
            value += '\"';
            i += 2;
            c = data.charAt(i);
          }
        }
      }
      while (c != eof && c != '\"');

      if (c == eof) {
        throw "Unexpected end of data, double-quote expected";
      }

      c = data.charAt(++i);
    }
    else {
      // value without quotes
      while (c != eof && c != delimeter && c!= newline && c != ' ' && c != '\t' && c != '\r') {
        value += c;
        c = data.charAt(++i);
      }
    }

    // add the value to the array
    if (array.length <= row) 
      array.push(new Array());
    array[row].push(value);

    // skip whitespaces
    while (c == ' ' || c == '\t' || c == '\r') {
      c = data.charAt(++i);
    }

    // go to the next row or column
    if (c == delimeter) {
      // to the next column
      col++;
    }
    else if (c == newline) {
      // to the next row
      col = 0;
      row++;
    }
    else if (c != eof) {
      // unexpected character
      throw "Delimiter expected after character " + i;
    }

    // go to the next character
    c = data.charAt(++i);
  }  

  return array;
}
/**
*将CSV(逗号分隔值)格式的数据转换为javascript数组。
*
*值由逗号分隔,或由自定义的单字符分隔符分隔。
*行由新行字符分隔。
*
*将忽略前导空格和尾随空格以及制表符。
*值可以选择用双引号括起来。
*包含特殊字符(逗号、双引号或新行)的值
*必须用双引号括起来。
*嵌入的双引号必须由一对连续的
*双引号。
*
*用法示例:
*var csv='“x”,“y”,“z”\n12.3,2.3,8.7\n4.5,1.2,-5.6\n';
*var阵列=CSV2阵列(csv);
*  
*作者:何塞·德容,2010年
* 
*@param{string}data以CSV格式显示数据。
*@param{string}delimeter[可选]自定义delimeter.逗号,默认为'
*Delimeter必须是单个字符。
*@return{Array}Array包含数据的二维数组
*@throw{String}error当出现错误时,该方法会抛出错误
*提供的数据中存在错误。
*/ 
功能csv2array(数据、测力计){
//取回delimeter
如果(delimeter==未定义)
delimeter=',';
如果(delimeter和delimeter.length>1)
delimeter=',';
//初始化变量
变量换行符='\n';
var eof=“”;
var i=0;
var c=数据特征(i);
var行=0;
var-col=0;
var数组=新数组();
而(c!=eof){
//跳过空白
而(c=''| | c='\t'| | c='\r'){
c=data.charAt(++i);//读取下一个字符
}
//获得价值
var值=”;
如果(c=='\'){
//用双引号括起来的值
c=数据字符(++i);
做{
如果(c!=“\”){
//读取一个常规字符并转到下一个字符
值+=c;
c=数据字符(++i);
}
如果(c=='\'){
//检查转义的双引号
var cnext=data.charAt(i+1);
如果(cnext=='\''){
//这是一个转义的双引号。
//在值中添加双引号,并向前移动两个字符。
值+=“\”;
i+=2;
c=数据字符(i);
}
}
}
而(c!=eof&&c!='\'');
如果(c==eof){
抛出“数据意外结束,需要双引号”;
}
c=数据字符(++i);
}
否则{
//不带引号的值
而(c!=eof&&c!=delimeter&&c!=newline&&c!=''&&c!='\t'&&c!='\r'){
值+=c;
c=数据字符(++i);
}
}
//将值添加到数组中

如果(array.length,这里有一个可能的解决方案:

console.log(array2d); // [[name, age], ["joe", 35], ["martha", 28]] const out = []; const propsRow = array2d[0]; array2d.forEach((row, i) => { if (i === 0) { return; } const addMe: any = {}; row.forEach((datum, j) => addMe[propsRow[j]] = datum); out.push(addMe); }); console.log(out); // [{name: "joe", age: 35}, {name: "martha", age: 28}]