最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to extract information in a TSV file and save it in an array in JavaScript ? - Stack Overflow

programmeradmin3浏览0评论

I'm running into a problem. If I have only tsv's file name. How can i extract all its information and save it in an array, say X, where each row in the tsv file is represented by an array, say y, where X is an array of ys.

ALso how can i do this if i don't know the headers of columns names ?

I'm running into a problem. If I have only tsv's file name. How can i extract all its information and save it in an array, say X, where each row in the tsv file is represented by an array, say y, where X is an array of ys.

ALso how can i do this if i don't know the headers of columns names ?

Share Improve this question asked Apr 23, 2013 at 18:52 Fawaz AlazemiFawaz Alazemi 631 gold badge1 silver badge3 bronze badges 2
  • 1 Have you tried anything? – Niet the Dark Absol Commented Apr 23, 2013 at 18:55
  • 1 is this server-side javascript? Access to files is pretty limited on the client side – colestrode Commented Apr 23, 2013 at 19:02
Add a ment  | 

7 Answers 7

Reset to default 5

You're going to need to use AJAX or just pure XMLHttpRequest.

http://d3js/ has a built-in tsv reader that does basically exactly what you want.

The syntax is

d3.tsv("file.tsv", function(data) {
    // use data here
});

The data variable is an array of objects with key/value pairs where the first row in the file is read in as the keys. So, for example

Number Awesomeness
1      5
2      3

will return [{"Number":1, "Awesomeness":5}, {"Number":2, "Awesomeness":3}].

// get file contents, store in var str
var x = str.split('\n');
for (var i=0; i<x.length; i++) {
    y = x[i].split('\t');
    x[i] = y;
}

console.debug(x);

For help on how to get the file contents, you'll need to specify where these files will be located (on the client machine, server, etc.).

If the files are located on the client machine, you might have a rough road ahead of you.

If the files are located on the server, you'll need to do an AJAX request to get the file contents.

Sticking this here so I can find it next time I need it:

// parse_tsv(tsvstring, function (row) { do something with row })
function parse_tsv(s, f) {
  var ix_end = 0;
  for (var ix=0; ix<s.length; ix=ix_end+1) {
    ix_end = s.indexOf('\n', ix);
    if (ix_end == -1) {
      ix_end = s.length;
    }
    var row = s.substring(ix, ix_end-1).split('\t');
    f(row);
  }
}

It's better than the accepted answer because it doesn't force building an array of lines in memory, but rather build little arrays one by one. In situations with large TSV, this can be helpful. Of course you could still build the array with the callback if that's what you need.

You don't have to use D3, JQuery or any another framework for this. Plain and simple JavaScript (AJAX technique):

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
                var arrayWithValues = xhttp.responseText.trim().split('\t');
                console.log(arrayWithValues);
        };
};
xhttp.open("GET", "/some.tsv", true);
xhttp.send();

Warning Dont create it by you own or be sure to takes into account all exceptions.

Typescript code

import parser from "csvtojson";

/**
 * - Takes into account \t and \n inside cells
 * - Remove empty columns
 * - Remove empty rows
 * - Trim cells
 */
export async function parseSheetStringInJSON(
  tsvString: string
): Promise<Record<string, string>[]> {
  function removeEmpty(obj: Object) {
    return Object.fromEntries(
      Object.entries(obj).filter(([_, v]) => Boolean(v))
    );
  }

  const parsed: Record<string, string>[] = await new Promise(
    (resolve, reject) =>
      parser({
        flatKeys: true,
        delimiter: "\t",
        trim: true,
      })
        .fromString(tsvString ?? "")
        .then(function (result) {
          const clean = result.map((el) => removeEmpty(el));
          resolve(clean);
        })
  );

  return parsed;
}

const tsvString = prompt("Please") ??
  'Key 1\tKey 2\n1.1\t"2.1\n2.11"\n1.2\t2.2\n"1.3\t1.33"\t3.3';

parseSheetStringInJSON(tsvString).then(console.log)
$result = array();
$fp = fopen('/path/to/file','r');
if (($headers = fgetcsv($fp, 0, "\t")) !== FALSE)
  if ($headers)
    while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) 
      if ($line)
        if (sizeof($line)==sizeof($headers))
          $result[] = array_bine($headers,$line);
fclose($fp);
print_r($result);

You can do it with Alasql library:

alasql('SELECT MATRIX * FROM TSV("mydata.tsv")',[],function(res){
    console.log(res);
});
发布评论

评论列表(0)

  1. 暂无评论