grid-js / gridjs

Advanced table plugin
https://gridjs.io
MIT License
4.42k stars 244 forks source link

load CSV or TSV data #37

Open setop opened 4 years ago

setop commented 4 years ago

feature

I'd like a way to load a CSV or TSV file as the data of the table. This is a common format for data exchange.

approach

The way it would be use could be a bit like server property but instead of expecting json data, expect comma/tab separated values.

alternatives

D3js propose d3.csv/d3.tsv functions which allow to load CSV/TSV file. It can be used to transform such format to JSON format on the fly.

afshinm commented 4 years ago

Agreed! added it to the roadmap.

fredEbho commented 4 years ago

Yea, we need it

DadiBit commented 7 months ago

TSV, CSV and likely any more niche formats (eg flatbuffers) can be implemented with the handle method:

new Grid({
    columns: ["Name", "Surname"],
    server: {
      url: 'http://example.com/api/v1/customers?format=tsv',
      handle: async response => {
        const text = await response.text(); // for binary data use .arrayBuffer(), or .body for a stream
        const lines = text.split('\n');
        return lines.map(line => line.split('\t'));
      },
      then: ([_head, ...data]) => data
    }
});

Here of course the head field could be used to manually map all column keys:

new Grid({
    columns: ["Name", "Surname"],
    server: {
      url: 'http://example.com/api/v1/customers?format=tsv',
      handle: async response => {
        const text = await response.text(); // for binary data use .arrayBuffer(), or .body for a stream
        const lines = text.split('\n');
        const [head, ...data] = lines.map(line => line.split('\t'));
        return data.map(row =>
          head.reduce((obj, k, i) => ({ ...obj, [k]: row[i] }), {})
        );
      },
      then: data => data.map((row: any) => [ row.Name, row.Surname ]
    }
});

Didn't implement the data type for demonstration purposes, the code works with any 2D TSV/CSV (replace '\t' with ',') data.

Still, perhaps a small utility/plugin to import could be a nice feature :smile: