0

I would like to parse a csv file from an http call and go thru each record.. For now I am using the below code to grab the whole content of .csv file, but I don't see any way that I can go thru each of the records on the .csv file.

    var body = [];
    request
    .get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=x')
    .on('data', function (chunk) {
        body.push(chunk);
    })
    .on('end', function () {
        body = body.join('');
        // body now contains csv contents as a string
        res.json(body);
    });

Is there any way that I can convert this into an array of objects or something similiar that I can grab each record seperately?

Thanks

Lulzim Fazlija
  • 865
  • 2
  • 16
  • 37

1 Answers1

-1

This is simple enough that you don't need a library. The function you want is the reverse of join: String.split().

var rows = body.split('\n');
for (var row = 0, rowCount = rows.length; row < rowCount; ++row) {
    var cols = rows[row].split(',');
    for (var col = 0, colCount = cols.length; col < colCount; ++col) {
        var element = cols[col].trim(); // Trim to remove whitespace.
    }
}
Yousef Amar
  • 651
  • 6
  • 19
  • 1
    Won't handle quotation marks which are valid and optional in CSV if the value itself has commas in it. – barry-johnson May 27 '16 at 17:51
  • @HisniFazlija I never tested it, but you get the idea. I edited my answer to remove the error. – Yousef Amar May 28 '16 at 01:22
  • 1
    @barry-johnson I'm aware of that, but it's unlikely when you know what your data is. Otherwise history repeats itself: http://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript – Yousef Amar May 28 '16 at 01:23
  • I would just note that future maintainers of the code on the other side of the API - even if both sides of the API call are a single platform today - could reasonably expect that the API's clients will handle CSV at full-spec. If it's just a throwaway tool, then yes, clearly whatever works is fine. – barry-johnson May 28 '16 at 16:11