sWarren
sWarren

Reputation: 473

How can I read a csv file to make it into a Json object?

I am reading a file using fs.readFile, I am then trying to separate it into an object with a corresponding key and value. Keys are: Agent,Time,Method,Resource,Version,Status

Values corresponds to this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML like Gecko) Chrome/69.0.3497.81 Safari/537.36,2018-10-09T23:31:00.080Z,GET,/logs,HTTP/1.1,200

(separated by comma).

For every line that looks like this:

Agent,Time,Method,Resource,Version,Status
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML like Gecko) Chrome/58.0.3029.110 Safari/537.36,2017-06-26T22:39:51.400Z,GET,/,HTTP/1.1,200
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0,2017-06-26T22:40:05.401Z,GET,/,HTTP/1.1,200
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0,2017-06-26T22:40:05.448Z,GET,/favicon.ico,HTTP/1.1,200
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0,2017-06-26T22:40:05.468Z,GET,/favicon.ico,HTTP/1.1,200

how can I assign them to keys in an object so that it looks like this:

 {
        "Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML like Gecko) Chrome/58.0.3029.110 Safari/537.36",
        "Time": "2017-06-26T22:39:51.400Z",
        "Method": "GET",
        "Resource": "/",
        "Version": "HTTP/1.1"
        "Status": "200"
      },

I want to be able to write code that makes the object above, for every line of data I receive.

So far I have got this:

fs.readFile('./log.csv','utf-8', function (err, data) {
        if (err) throw err;
        var lines = data.split('\n'); //splits my data into substrings that are in one big array.

This splits every line I get into a giant array, but then I'm lost.... I imagine I can use a for loop to go through each line in order to split it up? But I am a noob and am struggling. Thanks in advance for your help!

Upvotes: 2

Views: 48

Answers (1)

Timothy Chen
Timothy Chen

Reputation: 374

This GitHub gist should help you out! Since you've already read in the CSV, you probably just need to do this:

  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);

  }

  // result is now a javascript object here

Upvotes: 1

Related Questions