无法使用Baby Parse将csv解析为json

时间:2016-01-17 19:41:24

标签: angularjs json node.js csv papaparse

我正在尝试使用婴儿解析(从Papa Parse分支)获取csv文件并将数据解析为Json。 我正在测试的csv文件很直接:

Column1,Column2,Column3
1,2,3
3,2,1

到目前为止,我使用 ng-file-upload 成功加载文件,以通过浏览器加载csv文件。

我现在正尝试使用婴儿解析来获取此文件并将数据转换为JSON。

以下是我到目前为止:

控制器

// Watch for a csv file being uploaded.
$scope.$watch(function() {
    return $scope.file
    }, function(){
        $scope.upload($scope.file);
});

$scope.upload = function(file){
            if(file){
                Upload.upload({
                    url: 'api/admin/uploadCsv',
                    method: 'POST',
                    data: {userId: $scope.user._id},
                    file: file
                }).progress(function(evt){
                    console.log("firing");
                }).success(function(data){

                }).error(function(error){
                    console.log(error);
                })
            }
        };

在文件上传时,调用上传功能并调用服务器控制器。 上传的文件传递给上传函数,然后我尝试传递给解析方法。

module.exports.uploadCsv = function(req, res){
    var file = req.files.file;
    var userId = req.body.userId;

    parsed = babyparse.parse(file.path, babyParseConfig);
    console.log("data is " + (JSON.stringify(parsed.data)));
    ...

console.log输出以下内容:

data is {"data":[],"errors":[],"meta":{"delimiter":",","linebreak":"\n","aborted":false,"truncated":false,"fields":["..\\App\\uploads\\565b8feecddbb1e41b7aa839test.csv"]}}

我无法理解为什么数据:[]是空的,因为csv文件看起来像。

1 个答案:

答案 0 :(得分:0)

使用此处提供的答案(how to give file name a input in baby parser),我已经让解析器工作了。 以下是我最终的结果:

   var uploadcontent = fs.readFileSync(targetPath, { encoding: 'binary' });
   var parsed = babyparse.parse(uploadcontent);
   console.log((JSON.stringify(parsed)));

请注意,uploadContent是我保存文件的目录的路径,而不是文件本身。

以上输出以下

{"data":[["Column1","Column2","Column3"],["1","2","3"],["3","2","1"]],"errors":[],"meta":{"delimiter":",","linebreak":"\r\n","aborted":false,"truncated":false}}

以上内容可以改进为类似console.log((JSON.stringify(parsed.data)));的内容 获取数据。

相关问题