我知道我没有正确分开。我知道我需要尝试替换逗号后没有空格。
CSV文件:
if(isFinite(a)){
alert('This is number.');
}
else alert('This is not number.')
movieId,title,genre
1,"American President, The (1995)",Comedy|Drama|Romance
2,"Creation, The creator(xxxx)",Comedy|Drama|Romance
3,"Destruction, The destroyer(xxxxx)",Comedy|Drama|Romance
function csv_json(csvFile) {
const _ = require('lodash');
const fs = require('fs')
const csvData = fs.readFileSync(csvFile, 'utf8');
'use strict';
var csvObject = csvToObjectArray(csvData);
// console.log(csvObject);
function csvToObjectArray(data) {
var csvRowArray = data.split(/\n/); // spilt by new lines
var headerCellArray = trimQuotes(csvRowArray.shift().split(','));
var objectArray = [];
while (csvRowArray.length) {
var rowCellArray = trimQuotes(csvRowArray.shift().split(','));
var rowObject = _.zipObject(headerCellArray, rowCellArray);
objectArray.push(rowObject);
}
return objectArray;
}
function trimQuotes(stringArray) {
for (var i = 0; i < stringArray.length; i++) {
stringArray[i] = _.trim(stringArray[i], '"');
}
return stringArray;
}
return csvObject
}
module.exports = csv_json ;
我希望:
//js file
const mod = require('./syncCsv_Json.js');
const data = mod('./movieTest.csv')
const fs = require('fs')
console.log(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)' },
{ movieId: '', title: undefined, genre: undefined } ]
*/
答案 0 :(得分:0)
由于字段可以包含定界符(逗号),所以简单的行拆分是没有用的。因此,最好使用已经证明的解析器和转换器。例如,Keyang/node-csvtojson
:
csv()
.fromString(`movieId,title,genre
1,"American President, The (1995)",Comedy|Drama|Romance
2,"Creation, The creator(xxxx)",Comedy|Drama|Romance
3,"Destruction, The destroyer(xxxxx)",Comedy|Drama|Romance`)
.subscribe((jsonObj) => {
jsonObj.genre = jsonObj.genre.split('|')
})
.then(function(res) {
console.log(res)
})
<script src="https://cdn.rawgit.com/Keyang/node-csvtojson/d41f44aa/browser/csvtojson.min.js"></script>