0

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
     }
1
  • var lines=csv.split(/\r?\n/); try this Commented Apr 13, 2016 at 4:04

3 Answers 3

8

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/);
Sign up to request clarification or add additional context in comments.

Comments

0

Use trim() to remove \r

obj[headers[j].trim()] = currentline[j].trim();

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.