将CSV解析为哈希数组 [英] Parsing CSV to Array of Hashes

查看:76
本文介绍了将CSV解析为哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析CSV文件并创建一个哈希数组.我使用自己的代码实现了它,但我认为它不是最佳的.我正在尝试使用 CSV-Parser ,但仅输出数组数组(而不是哈希数组)/对象).

I am trying to parse a CSV file and create an array of hashes. I implemented it using my own code but I don't think it is optimal. I am trying to use CSV-Parser but am only outputting an Array of Array's (not an Array of Hashes/Objects).

这是我第一次尝试不使用该库的示例:

Here is an example of my first attempt without the library:

var fs = require('fs');
var readCSVData = function(data){
  var contactsArray = data.split("\n"); 
  var contactsArrayOfHashes = [];

for(var i=1; i < contactsArray.length; i++){
        var singleData = contactsArray[i].split(",");   

            contactsArrayOfHashes.push({
                first_name: singleData[0],
                last_name: singleData[1],
                months_since_contact: singleData[2],
                email_address: singleData[3]
            });
    }
    return contactsArrayOfHashes;
};

fs.readFile("contacts.csv","utf8", function(err, data){

    var csvData = readCSVData(data);
    console.log(csvData);       

});

这是我尝试使用CSV包的方法(这是我仅获得数组数组的地方)

Here is my attempt with the CSV Package (this is where I am only getting an Array of Arrays)

var fs = require('fs');
var csv = require("csv");

fs.readFile("contacts.csv","utf8", function(err, data){
    var friendsList = [];
    var csvData = readCSVData(data);
    csv.parse(data, function(err, parseData){
        for(var i=1; i < parseData.length; i++){
            friendsList.push(parseData[i]);
        }
    })

console.log(friendsList);

});

CSV文件:

first_name,last_name,months_since_contact,email_address
John,Doe,0,john@john.com

如何使用CSV npm创建哈希数组?有没有办法用列映射我的数组索引?

How can I create an Array of Hashes using the CSV npm? Is there a way to map my array indexes with columns?

理想情况下,我想将列映射到行

Ideally, I would like to map columns to rows

ex:我的数组看起来像是数组,但是它们被映射到我的CSV文件中的主要字段,如下所示:

ex: my Array's appear to be Array's but they are mapped to my main fields in my CSV File like this:

var CSVData = [John,Doe,0,john@john.com]
CSVData[0]["email_address"] outputs --> john@john.com

我相信我以前在ruby的 CSV类

I believe I've used this format before with ruby's CSV Class

推荐答案

来自文档:

解析器选项

  • columns:作为数组的字段列表,用户定义的回调接受第一行并返回列名;如果在第一条CSV行中自动发现,则返回true,默认为null,在某种意义上影响结果数据集记录将是对象而不是数组.

Parser options

  • columns: List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays.

这篇关于将CSV解析为哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆