【问题标题】:Reading from a CSV File to JSON returns an empty array从 CSV 文件读取到 JSON 会返回一个空数组
【发布时间】:2017-10-05 04:19:26
【问题描述】:

所以我有这个函数将 json 对象打印为字符串:

GetAllArticles: (req, res) => {
        var allArticles = getAllArticles();

        res.setHeader("Content-Type", 'application/json');
        res.write(JSON.stringify(allArticles));  //cast object to string

        res.end();
}

这是我的 getAllArticles:

function getAllArticles() {
    var result = [];
    result.push(new Article('Gummistiefel', 100, 34.99));
    result.push(new Article('Regenmantel', 10, 124.99));
    result.push(new Article('HTML5 Buch', 25, 4.99));

    //creates a test file
    var json2csv = require('json2csv');
    var fs = require('fs');
    var fields = ["articleName", "quantity","price"];

    var csv2 = json2csv({ data: result, fields: fields });

    fs.writeFile('file.csv', csv2, function (err) {
        if (err) throw err;
        console.log('file saved');
    });

    result = [];//clear the array to save new articles

    //load file
    const csvFilePath = 'file.csv'
    const csv = require('csvtojson')
    csv()
        .fromFile(csvFilePath)
        .on('json', (jsonObj) => { 

            result.push(jsonObj);
        })
        .on('done', (error) => {
             console.log('end');
        })



    return result;
}

文章:

function Article(articleName, quantity, price) {
    this.articleName = articleName;
    this.quantity = quantity;
    this.price = price;
}

网页上的输出是:[] 所以我检查了加载的 jsonObject 是否在数组中,但在我将它们转换为字符串后,输出只是“[]”..

【问题讨论】:

  • 验证stringify之前的allArticles中是否有对象。
  • 为什么这个标签是 asp-net-web-api
  • @Alex 对不起我的错。我对其进行了编辑。在所有文章中显然是空的,因为长度未定义。我在 on("done") 中打印了结果数组,它打印了 3 篇文章,但是当我返回它时,allArticles 是未定义的
  • @Gururaj 显然不是,而是返回的数组...
  • @KeyNavas - 总结不正确。如果您注释掉将数组重置为空的行会发生什么。函数中的最后一个 return 语句应该告诉你返回的是什么。

标签: javascript json node.js csv


【解决方案1】:

这是异步代码的经典现金

你需要改变 getAllArticles

function getAllArticles() {
    return new Promise((resolve) => {
        var result = [];
        result.push(new Article('Gummistiefel', 100, 34.99));
        result.push(new Article('Regenmantel', 10, 124.99));
        result.push(new Article('HTML5 Buch', 25, 4.99));

        //creates a test file
        var json2csv = require('json2csv');
        var fs = require('fs');
        var fields = ["articleName", "quantity","price"];

        var csv2 = json2csv({ data: result, fields: fields });

        fs.writeFile('file.csv', csv2, function (err) {
            if (err) throw err;
            console.log('file saved');

            result = [];//clear the array to save new articles

            //load file
            const csvFilePath = 'file.csv'
            const csv = require('csvtojson')
            csv()
                .fromFile(csvFilePath)
                .on('json', (jsonObj) => { 
                    result.push(jsonObj);
                })
                .on('done', (error) => {
                     resolve(result);
                })

        });
    })
}

为了你的路线

GetAllArticles: (req, res) => {
    getAllArticles().then((result) => {
        res.setHeader("Content-Type", 'application/json');
        res.write(JSON.stringify(result));  //cast object to string
        res.end();
    });  
}

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2018-11-21
    • 2020-01-13
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多