8

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.

Greg Venech
  • 8,062
  • 2
  • 19
  • 29
Karthik Prasad
  • 141
  • 1
  • 1
  • 7

5 Answers5

12

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);
    }
})
KiraLT
  • 2,385
  • 1
  • 24
  • 36
6

Fetch is 100% work with .csv file (or even api with req.query). 'content-type': 'text/csv' must be addressed in the fetch's headers:{}, and use res.text() instead of res.json() to interpret data.

const downloadCsv = async () => {
    try {
        const target = `https://SOME_DOMAIN.com/data/csv/addresses.csv`; //file
        //const target = `https://SOME_DOMAIN.com/api/data/log_csv?$"queryString"`; //target can also be api with req.query
        
        const res = await fetch(target, {
            method: 'get',
            headers: {
                'content-type': 'text/csv;charset=UTF-8',
                //'Authorization': //in case you need authorisation
            }
        });

        if (res.status === 200) {

            const data = await res.text();
            console.log(data);

        } else {
            console.log(`Error code ${res.status}`);
        }
    } catch (err) {
        console.log(err)
    }
}
2

pretty easy,

GET the url, with normal fetch req, and first convert response to text and then it's done

fetch('sample-url.csv')
  .then((response) => response.text())
  .then((data) => console.log(data));
0

CSV is not a JSON file type, so you cant parse as a json text. you can check how to parse CSV text in javascript here : Example JavaScript code to parse CSV data

Tinsae
  • 577
  • 5
  • 10
0

I would use the following method and insert it where you are supposed console.log the data.

const parseCSV = (data) => {
  // create empty array
  const csvData = [];
  
  // this will return each line as an individual String
  const lines = data.split("\n");
  
  // loop through the lines and return an array of individual   
  // Strings within the line that are separated by a comma
  
  for (let i = 0; i < lines.length; i++) {
      csvData[i] = lines[i].split(",");
  }
  
  // return an array of arrays 2D array
  // e.g [ [1,2,3], [3,4,5], [6,7,8] ]
  return csvData;
};
Dula
  • 3
  • 4