简体   繁体   中英

How to parse CSV with node.js?

I'm trying to follow an example of a streamgraphs in highcharts, link , but it says "parsed with node.js" instead of giving out the file/explaining how to do it.

I need to go from a csv formatted like this:

Category, Finland, Austria
1,        53,      29
2,        77,      88

To this in my js file:

series: [{
    name: "Finland",
    data: [
      53, 77
    ]
  }, {
    name: "Austria",
    data: [
      29, 88
    ]
  }, 

EDIT: but how do I actually merge it with the javascript script in highcharts ( here )?

Try this:

const { readFileSync } = require('fs')
let csv = readFileSync('path/to/your/file.csv', 'utf-8')
const series = []
csv = csv.split('\n')
let headers = csv.shift().split(',')
headers.shift()
for (let i = 0; i < headers.length; i++) {
  const data = []
  for (let j = 0; j < csv.length; j++)
    data.push(csv[j].split(',')[i + 1].trim())
  csv[i].split(',')
  series.push({
    name: headers[i].trim(),
    data
  })
}
console.log(series)

I'm trying to follow an example of a streamgraphs in highcharts, link , but it says "parsed with node.js" instead of giving out the file/explaining how to do it.

I need to go from a csv formatted like this:

Category, Finland, Austria
1,        53,      29
2,        77,      88

To this in my js file:

series: [{
    name: "Finland",
    data: [
      53, 77
    ]
  }, {
    name: "Austria",
    data: [
      29, 88
    ]
  }, 

EDIT: but how do I actually merge it with the javascript script in highcharts ( here )?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM