【问题标题】:Unable to use PapaParse 'unparse' to convert JSON to CSV无法使用 PapaParse 'unparse' 将 JSON 转换为 CSV
【发布时间】:2016-05-09 07:05:30
【问题描述】:

我正在尝试使用 babyParse 将 JSON 对象转换为 CSV 并将生成的 csv 格式输出到系统上的文件中。

module.exports.downloadItemCsv = function(req, res){
    Item.find({})
        .sort({date:-1})
        .exec(function(err, allItems){
            if(err){
                res.error(err)
            } else{

                var configuration = {
                    quotes: false,
                    delimiter: ",",
                    newline: "\r\n"
                };

                console.log(allItems);
                console.log("Adding items to object.");
                var csv = baby.unparse(allItems, configuration);

                var targetPath = path.join(__dirname,"../../uploads/" + "newFile01");

                fs.writeFile(targetPath, csv, function(err){
                   if(err){
                       console.log("Write complete!")
                   }
                });

                console.log("The file was saved!");
                res.json({status: 200})
            }
        })
};

console.log(allItems); 输出正确的 JSON 对象,但是当我为 csv 变量执行 console.log 时,输出似乎是来自婴儿 Parse 模块的函数页面。

据我在 PapaParse 文档中所知,我应该只需要在 var csv = baby.unparse(allItems, configuration); 行中传递 JSON 对象。

一旦我在变量“csv”中获得了未解析的数据,我应该能够将 csv 写入文件。有谁知道为什么 JSON 对象没有被解析为 csv 对象?

allItems 中的数据如下所示:

[ { __v: 0,
    itemId: 2507,
    item: 'TEST',
    description: 'TEST',
    brand: 'TEST',
    category: 'TEST',
    subcategory: 'TEST',
    size: '10',
    gender: 'F',
    costPrice: 10,
    salePrice: 10,
    saleDate: '2016-01-31',
    purchaseDate: '2016-01-31',
    _id: 56ae7972049ce640150453b7 } ]

下面是填充到变量“csv”中的结果。完整的结果太大了,不能放在下面。

$__,isNew,errors,_doc,$__original_save,save,_pres,_posts,db,discriminators,__v,id,_id,purchaseDate,saleDate,salePrice,costPrice,gender,size,subcategory,category,brand,description,item,itemId,schema,collection,$__handleSave,$__save,$__delta,$__version,increment,$__where,remove,model,on,once,emit,listeners,removeListener,setMaxListeners,removeAllListeners,addListener,$__buildDoc,init,$__storeShard,hook,pre,post,removePre,removePost,_lazySetupHooks,update,set,$__shouldModify,$__set,getValue,setValue,get,$__path,markModified,modifiedPaths,isModified,$isDefault,isDirectModified,isInit,isSelected,validate,$__validate,validateSync,invalidate,$markValid,$isValid,$__reset,$__dirty,$__setSchema,$__getArrayPathsToValidate,$__getAllSubdocs,$__registerHooksFromSchema,$__handleReject,$toObject,toObject,toJSON,inspect,toString,equals,populate,execPopulate,populated,depopulate,$__fullPath
[object Object],false,,[object Object],"function () {
      var self = this
        , hookArgs // arguments eventually passed to the hook - are mutable
        , lastArg = arguments[arguments.length-1]
        , pres = this._pres[name]
        , posts = this._posts[name]
        , _total = pres.length
        , _current = -1
        , _asyncsLeft = proto[name].numAsyncPres
        , _asyncsDone = function(err) {
            if (err) {
              return handleError(err);
            }
            --_asyncsLeft || _done.apply(self, hookArgs);
          }
        , handleError = function(err) {
            if ('function' == typeof lastArg)
              return lastArg(err);
            if (errorCb) return errorCb.call(self, err);
            throw err;

【问题讨论】:

    标签: json node.js export-to-csv papaparse


    【解决方案1】:

    问题与 allItems 是 Mongoose 文档的集合有关,而不是普通的 javascript 对象。您可以使用.toObject() 转换这些对象,或者简单地将lean 选项添加到您的查询中:

    module.exports.downloadItemCsv = function(req, res){
        Item.find({})
            .sort({date:-1})
            .lean()
            .exec(function(err, allItems){
    
            ...
        });
    };
    

    【讨论】:

    • 您好,Cviejo,感谢以上反馈;我将在今天晚些时候对此进行测试。您能告诉我为什么在将“allItems”记录到控制台时问题不明显吗?到目前为止,这通常是我知道我正在使用的内容的方式。最好理解为什么它没有给出真实的画面。
    • 当然。长话短说:console.log 将打印出该特定对象所具有的任何toString() 实现的结果。因此在内部,当您在 mongoose 文档上调用 toString() 时,它会将所有相关数据与 mongoose 方法和属性分开并返回。您正在使用的这个库 babyparse / papaparse 正在解析对象,它无法判断哪些属性与猫鼬相关,这是您看到的意外输出。
    • 添加 .lean() 就像一个魅力。感谢您在其目的背后缺少的部分/解释。
    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2019-02-03
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多