gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:41:03 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com