3

I am reading a csv file and following are csv file data

name, age, addr1 , addr2
test, 20 , "unit 1, test address, epp" , "test address 2"

Now i am making an object using header. see below code

var lines = loadedstring.split('\n');
    console.log(JSON.stringify(lines));
    var headers = lines[0].split(',');
    var jsonObj = [];
    for (var i = 1; i < lines.length; i++) {
        var data = lines[i].split(',');
        var obj = {};
        for (var j = 0; j < data.length; j++) {
            obj[headers[j].trim()] = data[j].trim();
        }
        jsonObj.push(obj);
    }
    console.log(JSON.stringify(jsonObj));

Butt problem is that how can i handle the commas which are in double as you see above in sample data. I want to ignore all the commas which are in double quotes. Don't want to split if comma within double quote.

Salman
  • 333
  • 4
  • 18
  • You could use RegEx – anteAdamovic Oct 11 '17 at 09:20
  • 2
    Try this solution https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data – gurvinder372 Oct 11 '17 at 09:25
  • Possible duplicate of [How can I parse a CSV string with Javascript, which contains comma in data?](https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data) – ADreNaLiNe-DJ Oct 11 '17 at 09:27

0 Answers0