Skip to content Skip to sidebar Skip to footer

How To Parse Csv From Github?

jQuery.ajax({ url: 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv', type:

Solution 1:

Parsing CSV is not always as simple as doing "...".split(','). And the file here is a perfect example of that. Some fields contain a ,, and thus are wrapped in quotes.

I suggest using Papa Parse which will handle that for you. I've used it many times before, it saved me a lot of headaches!

$.ajax({
    url: "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/6eae5b65a32b679efacf95a2867648330f83a871/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv",
    success: function(csv) {
        const output = Papa.parse(csv, {
          header: true, // Convert rows to Objects using headers as properties
        });
        if (output.data) {
          console.log(output.data);
        } else {
          console.log(output.errors);
        }
    },
    error: function(jqXHR, textStatus, errorThrow){
        console.log(textStatus);
    }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>

Solution 2:

You have to use dataType as text and then run split with double for loop to get the data as an array of JS objects:

jQuery.ajax({
    url: "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv",
    type: 'get',
    dataType: 'text',
    success: function(data) {
        let lines = data.split('\n');
        let fields = lines[0].split(',');
        
        let output = [];
        
        for(let i = 1; i < lines.length; i++){
           let current = lines[i].split(',');
           let doc = {};
           for(let j = 0; j < fields.length; j++){
               doc[fields[j]] = current[j];
           }
           output.push(doc);
        }       
        
        console.log(output);
    },
    error: function(jqXHR, textStatus, errorThrow){
        console.log(textStatus);
    }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Post a Comment for "How To Parse Csv From Github?"