将csv数据转换为数组格式

时间:2018-04-02 06:56:10

标签: javascript jquery html json

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

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数据转换为上述格式才能形成单词cloud。如果可能,请附上代码。我在我的html页面中做了所有这些。谢谢。

4 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案:

var csv = "";
csv += "text weight\n";
csv += "Lorem 15\n";
csv += "Ipsum 9";

var lines = csv.split("\n");
var titles = lines[0].split(" ");
var data = new Array(lines.length - 1);

for (var i = 1; i < lines.length; i++) {
  data[i - 1] = {};
  lines[i] = lines[i].split(" ");
  for (var j = 0; j < titles.length; j++) {
    data[i - 1][titles[j]] = lines[i][j];
  }
}

console.log(data);

答案 1 :(得分:1)

这是ES6中可能的解决方案:

const csv2json = (str, delimiter = ',') => {
  const titles = str.slice(0, str.indexOf('\n')).split(delimiter);
  const rows = str.slice(str.indexOf('\n') + 1).split('\n');
  return rows.map(row => {
    const values = row.split(delimiter);
    return titles.reduce((object, curr, i) => (object[curr] = values[i], object), {})
  });
};


let csv = "text weight\nLorem 15\nIpsum 9";
let word_array = csv2json(csv,' ');
console.log(word_array)

答案 2 :(得分:0)

您可以使用以下代码

从CSV To Array获取数据
 /**
 * 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;
}

工作示例演示链接: http://www.speqmath.com/tutorials/csv2array/

答案 3 :(得分:0)

这是我为此编写的一些代码:

const lineRegex = /((\\\n)|[^\n])+/g;
const datumRegex = /,?(("(\\"|.)+?")|([^",][^,]*))?/g;
const array2d: string[][] = rawCsvFile.match(lineRegex).map((row) => 
    row.match(datumRegex).map((datum) => datum.replace(/^,?"?|"$/g, "").trim()),
);

以上正则表达式将处理基准内的换行符以及转义的引号和引号逗号。而且,如果您要创建一个对象数组,其中每一行都是一个以第一行值作为属性名称的对象,则可以使用它。

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}]