代码之家  ›  专栏  ›  技术社区  ›  rob.m

如何从github解析csv?

  •  3
  • rob.m  · 技术社区  · 4 年前
    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: 'json',
        success: function(data) {
            console.log(data);
        },
        error: function(jqXHR, textStatus, errorThrow){
            alert("Error: " + jqXHR['responseText']);
        }
    });
    

    我需要格式为json的输出,但它会出错,基本上是试图解析这个

    https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv

    1 回复  |  直到 4 年前
        1
  •  1
  •   mickl    4 年前

    你必须使用 dataType 作为 text split 使用double for循环将数据获取为JS对象数组:

    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);
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        2
  •  2
  •   blex    4 年前

    "...".split(',') . 这里的文件是 perfect example of that . 有些字段包含 ,

    我建议使用 Papa Parse

    $.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",
        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);
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>