Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TSV to JSON Conversion in JavaScript
//var tsv is the TSV file with headers
function tsvJSON(tsv){
var lines=tsv.split("\n");
var result = [];
var headers=lines[0].split("\t");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split("\t");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
@lamuertepeluda
Copy link

lamuertepeluda commented Apr 16, 2019

Good, but maybe this is shorter?

      function tsvJSON(tsv) {
        const lines = tsv.split('\n');
        const headers = lines.slice(0, 1)[0].split('\t');
        return lines.slice(1, lines.length).map(line => {
          const data = line.split('\t');
          return headers.reduce((obj, nextKey, index) => {
            obj[nextKey] = data[index];
            return obj;
          }, {});
        });
      }

@phiferd
Copy link

phiferd commented Apr 22, 2020

Slightly cleaner. Replacing the first slice with shift(), which makes the second slice unnecessary.

      function tsvJSON(tsv) {
        const lines = tsv.split('\n');
        const headers = lines.shift().split('\t');
        return lines.map(line => {
          const data = line.split('\t');
          return headers.reduce((obj, nextKey, index) => {
            obj[nextKey] = data[index];
            return obj;
          }, {});
        });
      }

@gegeke
Copy link

gegeke commented Jul 9, 2020

Not really clean (but what function with reduce in it is ;) ), but no slices, no headers variable:

function tsvJSON(tsv) {
  return tsv.split('\n')
  .map(line => line.split('\t'))
  .reduce((a, c, i, d) => {
    if (i) {
      const item = Object.fromEntries(c.map((val, j) => [d[0][j], val]))
      return a ? [...a, item] : [item]
    }
  }, [])
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment