【问题标题】:Saving array as output file of any format将数组保存为任何格式的输出文件
【发布时间】:2020-03-02 04:11:36
【问题描述】:

我需要帮助来确定如何保存数组中的输出。我尝试将输出附加到 csv,但这给了我一个空的 csv 或一个为数组中的每个项目附加单词 [object] 的 csv。

这是我的数组中的输出示例:

{
      date: '2014-01-25',
      firstBoxerRating: [Array],
      firstBoxerWeight: 235.5,
      judges: [Array],
      links: [Object],
      location: 'Golden Nugget Casino, Atlantic City',
      metadata: '<a href="/en/judge/401833">Joseph Pasquale</a> 75-77 | <a href="/en/judge/401066">Tony Perez</a> 78-74 | <a href="/en/judge/401734">Barbara Perez</a> 78-74\n' +
        '<br>',
      numberOfRounds: [Array],
      outcome: 'win',
      rating: 20,
      referee: [Object],
      result: [Array],
      secondBoxer: [Object],
      secondBoxerLast6: [Array],
      secondBoxerRating: [Array],
      secondBoxerRecord: [Object],
      secondBoxerWeight: 236.5,
      titles: []
    },
    {
      date: '2014-05-16',
      firstBoxerRating: [Array],
      firstBoxerWeight: 240.75,
      judges: [Array],
      links: [Object],
      location: '2300 Arena, Philadelphia',
      metadata: '<a href="/en/judge/402009">Pierre Benoist</a> 79-73 | <a href="/en/judge/401245">Lynne Carter</a> 78-74 | <a href="/en/judge/677642">Eric Dali</a> 79-73\n' +
        '<br>',
      numberOfRounds: [Array],
      outcome: 'win',
      rating: 20,
      referee: [Object],
      result: [Array],
      secondBoxer: [Object],
      secondBoxerLast6: [Array],
      secondBoxerRating: [Array],
      secondBoxerRecord: [Object],
      secondBoxerWeight: 238,
      titles: []
    },
    {
      date: '2014-08-02',
      firstBoxerRating: [Array],
      firstBoxerWeight: 236.5,
      judges: [Array],
      links: [Object],
      location: 'Revel Resort, Atlantic City',
      metadata: '  time: 1:48\n' +
        ' | <a href="/en/judge/401683">Lindsey Page</a>\n' +
        '<br>Williams down three times\n' +
        '<br>',
      numberOfRounds: [Array],
      outcome: 'win',
      rating: 20,
      referee: [Object],
      result: [Array],
      secondBoxer: [Object],
      secondBoxerLast6: [Array],
      secondBoxerRating: [Array],
      secondBoxerRecord: [Object],
      secondBoxerWeight: 233,
      titles: []
    },
    {
      date: '2014-09-19',
      firstBoxerRating: [Array],
      firstBoxerWeight: 237,
      judges: [Array],
      links: [Object],
      location: "Harrah's Philadelphia, Chester",
      metadata: '  time: 1:34\n' +
        ' | <span>referee:</span> <a href="/en/referee/401364">Benjy Esteves Jr</a><span> | </span><a href="/en/judge/401043">Bernard Bruni</a> | <a href="/en/judge/400983">Larry Hazzard Jr</a> | <a href="/en/judge/402781">Alan Rubenstein</a>\n' +
        '<br>',
      numberOfRounds: [Array],
      outcome: 'win',
      rating: 20,
      referee: [Object],
      result: [Array],
      secondBoxer: [Object],
      secondBoxerLast6: [Array],
      secondBoxerRating: [Array],
      secondBoxerRecord: [Object],
      secondBoxerWeight: 288,
      titles: []
    },
    {
      date: '2014-11-14',
      firstBoxerRating: [Array],
      firstBoxerWeight: 244,
      judges: [Array],
      links: [Object],
      location: "Harrah's Philadelphia, Chester",
      metadata: '  time: 2:28\n' +
        ' | <span>referee:</span> <a href="/en/referee/401364">Benjy Esteves Jr</a><span> | </span><a href="/en/judge/677642">Eric Dali</a> | <a href="/en/judge/400983">Larry Hazzard Jr</a> | <a href="/en/judge/671032">Mike Somma</a>\n' +
        '<br>',
      numberOfRounds: [Array],
      outcome: 'win',
      rating: 40,
      referee: [Object],
      result: [Array],
      secondBoxer: [Object],
      secondBoxerLast6: [Array],
      secondBoxerRating: [Array],
      secondBoxerRecord: [Object],
      secondBoxerWeight: 209,
      titles: []
    },

我假设这个输出是一个 JSON 对象。

这是我用来产生这个输出的代码:

async function writeData() {
    const csv = require('csv-parser')
    const results = [];
    fs.createReadStream('C:\\Users\\User\\Documents\\testingclean.csv')
        .pipe(csv())
        .on('data',(data)=> results.push(data))
        .on('end', async () => {
          const cookieJar = await getCookieJar();
          const promises = [];
          results.forEach((data) => {
            promises.push(boxrec.getPersonById(cookieJar,data.id));
          })
          const fighters = await Promise.all(promises); // Fighters is an array
          fighters.forEach((fighter) => {
              console.log(fighter.output);
          })
        });
    };
try {
    writeData();
} catch (error) {
    console.log("Error in writeData: " + error);
}

【问题讨论】:

    标签: node.js json csv


    【解决方案1】:

    这样的事情应该可以工作。

    fighters.forEach((fighter) => {
        let data = '';
    
        for (const key in fighter.output) {
            if (Array.isArray(fighter.output[key])) {
                data += JSON.stringify(fighter.output[key]) + ',';
            } else if (typeof fighter.output[key] === 'object') {
                data += JSON.stringify(fighter.output[key]) + ',';
            } else {
                data += fighter.output[key] + ',';
            }
        }
        data = data.replace(/(^,)|(,$)/g, ""); // Remove trailing comma
        data += '\n'; // Add new line
    
        fs.appendFile('data.csv', data, (err) => {
            if (err) throw err;
        });
    });
    

    没有测试代码。此外,data.csv 文件可能需要一些时间来创建,具体取决于数据大小。 forEach 外观甚至会在 nodejs 完成写入文件之前完成。因此,程序可能会退出,但在后台写入可能会一直持续到完成。您必须维护async 执行部分。如何处理不在本题范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多