javascript - parse \r strings from CSV file


Keywords:javascript 


Question: 

I am reading a csv file in javascript by first spliting by newline then spiliting by comma. I am able to parse the whole of csv successfully but only one thing is left. i.e. the last one

I don't know how to remove those \r . The code I am using is

    function csvJSON(csv){
        var lines=csv.split("\n");
        var result = [];
        var headers=lines[0].split(",");
        for(var i=1;i<lines.length;i++){
            var obj = {};
            var currentline=lines[i].split(",");
            for(var j=0;j<headers.length;j++){
                  obj[headers[j]] = currentline[j];
            }
            result.push(obj);
         }
         return result; //JavaScript object
     }

3 Answers: 

By standard CSV lines are ended with CRLF ('\r\n'). But if you expect to support non-stardard line endings also test for others as well:

var lines=csv.split(/\r\n|\n|\r/);
 

Try this query,

    function csvJSON(csv){

     var lines=csv.replace(/(\r\n|\n|\r)/gm,"");

     var result = [];

     var headers=lines[0].split(",");

     for(var i=1;i<lines.length;i++){

      var obj = {};
      var currentline=lines[i].split(",");

     for(var j=0;j<headers.length;j++){
       obj[headers[j]] = currentline[j];
     }

      result.push(obj);

    }

     return result; //JavaScript object
    }
 

Try below code

var data='{"batting_score":"52","wickets":"0","runs_conceded":"12","catches":"0","stumps":"0","opposition":"v Pakistan","ground":"Dhaka","date":"18-Mar-12","match_result":"won","result_margin":"6 wickets","toss":"lost","batting_innings":"2nd"}'.replace(/\r/g,'');
var JsonData=JSON.parse(data);

now you can access properties like below

JsonData.batting_score //52