javascript - 如何修复 csv 到 json 转换器模块?

标签 javascript node.js

我不知道如何根据模块中的内容正确匹配标题和类型。

csv_json 模块有一个异常(exception),它不相应地匹配每个属性,即当标题中包含“The”时。

//csv文件

movieId,title,genre

1,"美国总统, The (1995)",喜剧|剧情|爱情 2,,,,Creation, The creator(xxxx),喜剧|剧情|爱情 3,《毁灭·毁灭者(xxxxx)》,喜剧|剧情|爱情


//csv_json module 
const readline = require('readline');
const fs = require('fs');

function readCsv(pathToFile) {
    return new Promise((resolve, reject) => {
        const csvReader = readline.createInterface({
            input: fs.createReadStream(pathToFile)
        });

        let headers;
        const rows = [];
        let tempRows = [];
        csvReader
            .on('line', row => {
                if (!headers) {
                    headers = row.split(','); // header name breed age
                } else {
                    rows.push(row.split(','));
                }
            })
            .on('close', () => {
                // then iterate through all of the "rows", matching them to the "headers"
                for (var i = 0; i < rows.length; i++) {
                    var obj = {};
                    var currentline = rows[i];

                    for (var j = 0; j < headers.length; j++) {
                        obj[headers[j]] = currentline[j]; //Kitty Siamese 14
                    }

                    tempRows.push(obj);
                }

                resolve(JSON.stringify(tempRows));
            });

        // This would be in place of the "return" statement you had before
    });
}

module.exports = readCsv;
//js file
const readCsv = require('./csvjson.js');

readCsv('movieTest.csv').then((data) => {
    console.log(data)
    let movieJson = JSON.parse(data);
    console.log(movieJson)


/*data output:
[{"movieId":"1","title":"\"American President","genre":" The (1995)\""},{"movieId":"2","title":"\"Creation","genre":" The creator(xxxx)\""},{"movieId":"3","title":"\"Destruction","genre":" The destroyer(xxxxx)\""}]

*/
/*movieJson output:
[ { movieId: '1',
    title: '"American President',
    genre: ' The (1995)"' },
  { movieId: '2',
    title: '"Creation',
    genre: ' The creator(xxxx)"' },
  { movieId: '3',
    title: '"Destruction',
    genre: ' The destroyer(xxxxx)"' } ]
*/
});

我希望输出匹配:

[ { movieId: '1',
    title: "American President, The (1995)",
    genre:'Comedy|Drama|Romance' },
  { movieId: '2',
    title: "The creator(xxxx) Creation",
    genre: ' Comedy|Drama|Romance' },
  { movieId: '3',
    title: "Destruction The destroyer(xxx)",
    genre: ' Comedy|Drama|Romance' } ]

最佳答案

这可能是因为您要在每次出现逗号时拆分每一行。

const row = '1,"American President, The (1995)",Comedy|Drama|Romance'
row.split(',')
// returns ["1", ""American President", " The (1995)"", "Comedy|Drama|Romance"]

尝试用 CSV 文件中其他任何地方都不会出现的唯一字符串替换每个没有后跟空格的逗号,然后拆分:

row.replace(/\,(\S)/g, '&unique;$1').split('&unique;')
// returns ["1", ""American President, The (1995)"", "Comedy|Drama|Romance"]

希望对您有所帮助! :)

关于javascript - 如何修复 csv 到 json 转换器模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402809/

相关文章:

JavaScript module.exports 回调

node.js - 如何在 Mongoose 模式中具有自动计算的属性

javascript - jQuery/JavaScript : Check all checkboxes but within a specific table only

javascript - 使用 Knockout.js 和 MVC 4 填充选择选项

javascript - 如何避免在 JavaScript 中对函数输出进行多个变量重新声明

javascript - 根据列中的值过滤 Google 表格

javascript - nodejs-如何使用node-opcua访问远程opc服务器?

javascript原型(prototype)链接 - 获取父级的父级

javascript - Jquery对具有特定attr值的所有元素的值求和

node.js - Azure Web应用程序 Node 部署,更改应用程序根目录?