Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to read a .csv file with Javascript fetch API?

Like

fetch('state_wise_data.csv')
   .then(response => response.json())
   .then(data => console.log(data))
   .catch(err => console.log(err))

Tried doing this but didn't work.

like image 960
Karthik Prasad Avatar asked Apr 15 '26 07:04

Karthik Prasad


1 Answers

First of all, CSV it's not a JSON. Fetch does not have CSV support, you will need to download CSV string (you can use response.text()) and use the third party CSV parser.

For parse CSV parser you can use papaparse:

"Isn't parsing CSV just String.split(',')?"

Heavens, no. Papa does it right. Just pass in the CSV string with an optional configuration.

Example:

const response = fetch('state_wise_data.csv')
   .then(response => response.text())
   .then(v => Papa.parse(v))
   .catch(err => console.log(err))

response.then(v => console.log(v))

It also supports file downloading:

Papa.parse('state_wise_data.csv', {
    download: true,
    complete: results => {
        console.log(results);
    }
})
like image 113
KiraLT Avatar answered Apr 17 '26 20:04

KiraLT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!