Jet*_*ohn 57 javascript csv json node.js express
我想将csv文件转换为json.我在用 .
示例CSV:
a,b,c,d
1,2,3,4
5,6,7,8
...
Run Code Online (Sandbox Code Playgroud)
期望的JSON:
{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
...
Run Code Online (Sandbox Code Playgroud)
我尝试了node-csv解析器库.但是输出就像数组一样,不像我预期的那样.
我正在使用Node 0.8和express.js,并希望了解如何轻松实现这一目标.
Key*_*ang 76
Node.js csvtojson模块是一个全面的nodejs csv解析器.它可以用来作为Node.js的应用程序库/命令行工具/或与帮助浏览器browserify或webpack.
源代码可以在https://github.com/Keyang/node-csvtojson找到
它速度快,内存消耗低,但功能强大,支持任何解析需求,具有丰富的API和易于阅读的文档.
详细的文档可以在这里找到
将它用作Node.js应用程序中的库(csvtojson@2.0.0 +):
npmnpm install --save csvtojson@latest
// require csvtojson
var csv = require("csvtojson");
// Convert a csv file with csvtojson
csv()
.fromFile(csvFilePath)
.then(function(jsonArrayObj){ //when parse finished, result will be emitted here.
console.log(jsonArrayObj);
})
// Parse large csv with stream / pipe (low mem consumption)
csv()
.fromStream(readableStream)
.subscribe(function(jsonObj){ //single json object will be emitted for each csv line
// parse each json asynchronousely
return new Promise(function(resolve,reject){
asyncStoreToDb(json,function(){resolve()})
})
})
//Use async / await
const jsonArray=await csv().fromFile(filePath);
Run Code Online (Sandbox Code Playgroud)
将其用作命令行工具:
sh# npm install csvtojson
sh# ./node_modules/csvtojson/bin/csvtojson ./youCsvFile.csv
Run Code Online (Sandbox Code Playgroud)
-要么-
sh# npm install -g csvtojson
sh# csvtojson ./yourCsvFile.csv
Run Code Online (Sandbox Code Playgroud)
对于高级用法:
sh# csvtojson --help
Run Code Online (Sandbox Code Playgroud)
您可以从上面的github页面中找到更多详细信息.
brn*_*nrd 20
您可以尝试使用underscore.js
首先使用toArray函数转换数组中的行:
var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);
Run Code Online (Sandbox Code Playgroud)
然后使用对象函数将数组对齐:
var json = _.object(letters, numbers);
Run Code Online (Sandbox Code Playgroud)
到那时,json var应包含以下内容:
{"a": 1,"b": 2,"c": 3,"d": 4}
Run Code Online (Sandbox Code Playgroud)
Jes*_*ess 11
这是一个不需要单独模块的解决方案.但是,它非常粗糙,并没有实现太多的错误处理.它也可以使用更多测试,但它会让你前进.如果要解析非常大的文件,可能需要寻找替代方法.另外,请参阅Ben Nadel的此解决方案.
/*
* Convert a CSV String to JSON
*/
exports.convert = function(csvString) {
var json = [];
var csvArray = csvString.split("\n");
// Remove the column names from csvArray into csvColumns.
// Also replace single quote with double quote (JSON needs double).
var csvColumns = JSON
.parse("[" + csvArray.shift().replace(/'/g, '"') + "]");
csvArray.forEach(function(csvRowString) {
var csvRow = csvRowString.split(",");
// Here we work on a single row.
// Create an object with all of the csvColumns as keys.
jsonRow = new Object();
for ( var colNum = 0; colNum < csvRow.length; colNum++) {
// Remove beginning and ending quotes since stringify will add them.
var colData = csvRow[colNum].replace(/^['"]|['"]$/g, "");
jsonRow[csvColumns[colNum]] = colData;
}
json.push(jsonRow);
});
return JSON.stringify(json);
};
Run Code Online (Sandbox Code Playgroud)
var csv2json = require('csv2json.js');
var CSV_STRING = "'col1','col2','col3'\n'1','2','3'\n'4','5','6'";
var JSON_STRING = '[{"col1":"1","col2":"2","col3":"3"},{"col1":"4","col2":"5","col3":"6"}]';
/* jasmine specs for csv2json */
describe('csv2json', function() {
it('should convert a csv string to a json string.', function() {
expect(csv2json.convert(CSV_STRING)).toEqual(
JSON_STRING);
});
});
Run Code Online (Sandbox Code Playgroud)
use*_*Fog 10
不得不做类似的事情,希望这会有所帮助.
// Node packages for file system
var fs = require('fs');
var path = require('path');
var filePath = path.join(__dirname, 'PATH_TO_CSV');
// Read CSV
var f = fs.readFileSync(filePath, {encoding: 'utf-8'},
function(err){console.log(err);});
// Split on row
f = f.split("\n");
// Get first row for column headers
headers = f.shift().split(",");
var json = [];
f.forEach(function(d){
// Loop through each row
tmp = {}
row = d.split(",")
for(var i = 0; i < headers.length; i++){
tmp[headers[i]] = row[i];
}
// Add object to list
json.push(tmp);
});
var outPath = path.join(__dirname, 'PATH_TO_JSON');
// Convert object to string, write json to file
fs.writeFileSync(outPath, JSON.stringify(json), 'utf8',
function(err){console.log(err);});
Run Code Online (Sandbox Code Playgroud)
使用ES6
const toJSON = csv => {
const lines = csv.split('\n')
const result = []
const headers = lines[0].split(',')
lines.map(l => {
const obj = {}
const line = l.split(',')
headers.map((h, i) => {
obj[h] = line[i]
})
result.push(obj)
})
return JSON.stringify(result)
}
const csv = `name,email,age
francis,francis@gmail.com,33
matty,mm@gmail.com,29`
const data = toJSON(csv)
console.log(data)
Run Code Online (Sandbox Code Playgroud)
输出
// [{"name":"name","email":"email","age":"age"},{"name":"francis","email":"francis@gmail.com","age":"33"},{"name":"matty","email":"mm@gmail.com","age":"29"}]
Run Code Online (Sandbox Code Playgroud)
使用lodash:
function csvToJson(csv) {
const content = csv.split('\n');
const header = content[0].split(',');
return _.tail(content).map((row) => {
return _.zipObject(header, row.split(','));
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83431 次 |
| 最近记录: |