Reputation: 139
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
}
Upvotes: 0
Views: 2686
Reputation: 1
Use trim()
to remove \r
obj[headers[j].trim()] = currentline[j].trim();
Upvotes: 0
Reputation: 1288
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
Upvotes: -1
Reputation: 900
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/);
Upvotes: 8