我正在尝试将 csv 文件转换为 json。我在用 。
示例 CSV:
a,b,c,d
1,2,3,4
5,6,7,8
...
所需的 JSON:
{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
...
我试过 node-csv 解析器库。但输出就像数组,不像我预期的那样。
我正在使用 Node 0.8 和 express.js,并希望获得有关如何轻松完成此操作的建议。
我正在尝试将 csv 文件转换为 json。我在用 。
示例 CSV:
a,b,c,d
1,2,3,4
5,6,7,8
...
所需的 JSON:
{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
...
我试过 node-csv 解析器库。但输出就像数组,不像我预期的那样。
我正在使用 Node 0.8 和 express.js,并希望获得有关如何轻松完成此操作的建议。
Node.jscsvtojsonmodule是一个综合的 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);
将其用作命令行工具:
sh# npm install csvtojson
sh# ./node_modules/csvtojson/bin/csvtojson ./youCsvFile.csv
-或者-
sh# npm install -g csvtojson
sh# csvtojson ./yourCsvFile.csv
高级用法:
sh# csvtojson --help
您可以从上面的 github 页面找到更多详细信息。
你可以尝试使用underscore.js
首先使用toArray函数转换数组中的行:
var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);
然后使用对象函数将数组对象在一起:
var json = _.object(letters, numbers);
到那时,json var 应该包含如下内容:
{"a": 1,"b": 2,"c": 3,"d": 4}
不得不做类似的事情,希望这会有所帮助。
// 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);});
这是一个不需要单独module的解决方案。但是,它非常粗糙,并没有实现太多的错误处理。它也可以使用更多的测试,但它会让你继续前进。如果您正在解析非常大的文件,您可能需要寻找替代方案。另外,请参阅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);
};
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);
    });
});
使用 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)
输出
// [{"name":"name","email":"email","age":"age"},{"name":"francis","email":"francis@gmail.com","age":"33"},{"name":"matty","email":"mm@gmail.com","age":"29"}]