如何读取csv文件以使其成为Json对象?

时间:2018-10-10 00:47:05

标签: javascript node.js express

我正在使用fs.readFile读取文件,然后尝试将其分离为具有相应键和值的对象。 键为:代理,时间,方法,资源,版本,状态

值对应于此: Mozilla / 5.0(Macintosh; Intel Mac OS X 10_13_6)AppleWebKit / 537.36(KHTML如Gecko)Chrome / 69.0.3497.81 Safari / 537.36,2018-10-09T23:31:00.080Z,GET,/ logs,HTTP / 1.1,200

(用逗号分隔)。

对于每行如下所示:

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

如何将它们分配给对象中的键,使其看起来像这样:

 {
        "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"
      },

对于我收到的每一行数据,我都希望能够编写使上方对象成为对象的代码。

到目前为止,我已经知道了:

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.

这会将我分成的每一行分成一个巨大的数组,但后来我迷路了... 我想我可以使用for循环遍历每一行以将其拆分?但是我是菜鸟,正在挣扎。预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

This GitHub gist应该可以帮助您!由于您已经阅读过CSV,因此您可能只需要这样做:

  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