All you need nodejs csv to json converter. * Large CSV data * Command Line Tool and Node.JS Lib * Complex/nested JSON * Easy Customised Parser * Stream based * multi CPU core support * Easy Usage * more!
Here is a free online csv to json service ultilising latest csvtojson module.
GitHub: https://github.com/Keyang/node-csvtojson
npm install -g csvtojson
npm install csvtojson --save
You can use File stream
//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function (jsonArray) {
console.log(jsonArray); //here is your result jsonarray
});
//read from file
require("fs").createReadStream("./file.csv").pipe(converter);
Or use fromFile convenient function
//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromFile("./file.csv",function(err,result){
});
To convert any CSV data from readable stream just simply pipe in the data.
//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({constructResult:false}); //for big csv data
//record_parsed will be emitted each csv row being processed
converter.on("record_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
});
require("request").get("http://csvwebserver").pipe(converter);
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromString(csvString, function(err,result){
//your code here
});
csvtojson
Example
csvtojson ./myCSVFile
Or use pipe:
cat myCSVFile | csvtojson
Check current version:
csvtojson version
Advanced usage with parameters support, check help:
csvtojson --help
The constructor of csv Converter allows parameters:
var converter=new require("csvtojson").Converter({
constructResult:false,
workerNum:4,
noheader:true
});
Following parameters are supported:
All parameters can be used in Command Line tool. see
csvtojson --help
To transform JSON result, (e.g. change value of one column), just simply add 'transform handler'.
var Converter=require("csvtojson").Converter;
var csvConverter=new Converter({});
csvConverter.transform=function(json,row,index){
json["rowIndex"]=index;
/* some other examples:
delete json["myfield"]; //remove a field
json["dateOfBirth"]=new Date(json["dateOfBirth"]); // convert a field type
*/
};
csvConverter.fromString(csvString,function(err,result){
//all result rows will add a field 'rowIndex' indicating the row number of the csv data:
/*
[{
field1:value1,
rowIndex: 0
}]
*/
});
As shown in example above, it is able to apply any changes to the result json which will be pushed to down stream and "record_parsed" event.
Asynchronouse transformation can be achieve either through "record_parsed" event or creating a Writable stream.
To transform data asynchronously, it is suggested to use csvtojson with Async Queue.
This mainly is used when transformation of each csv row needs be mashed with data retrieved from external such as database / server / file system.
However this approach will not change the json result pushed to downstream.
Here is an example:
var Conv=require("csvtojson").Converter;
var async=require("async");
var rs=require("fs").createReadStream("path/to/csv"); // or any readable stream to csv data.
var q=async.queue(function(json,callback){
//process the json asynchronously.
require("request").get("http://myserver/user/"+json.userId,function(err,user){
//do the data mash here
json.user=user;
callback();
});
},10);//10 concurrent worker same time
q.saturated=function(){
rs.pause(); //if queue is full, it is suggested to pause the readstream so csvtojson will suspend populating json data. It is ok to not to do so if CSV data is not very large.
}
q.empty=function(){
rs.resume();//Resume the paused readable stream. you may need check if the readable stream isPaused() (this is since node 0.12) or finished.
}
var conv=new Conv({construct:false});
conv.transform=function(json){
q.push(json);
};
conv.on("end_parsed",function(){
q.drain=function(){
//code when Queue process finished.
}
})
rs.pipe(conv);
In example above, the transformation will happen if one csv rown being processed. The related user info will be pulled from a web server and mashed into json result.
There will be at most 10 data transformation woker working concurrently with the help of Async Queue.
It is able to create a Writable stream (or Transform) which process data asynchronously. See Here for more details.
Below is an example of result tranformation which converts csv data to a column array rather than a JSON.
var Converter=require("csvtojson").Converter;
var columArrData=__dirname+"/data/columnArray";
var rs=fs.createReadStream(columArrData);
var result = {}
var csvConverter=new Converter();
//end_parsed will be emitted once parsing finished
csvConverter.on("end_parsed", function(jsonObj) {
console.log(result);
console.log("Finished parsing");
done();
});
//record_parsed will be emitted each time a row has been parsed.
csvConverter.on("record_parsed", function(resultRow, rawRow, rowIndex) {
for (var key in resultRow) {
if (!result[key] || !result[key] instanceof Array) {
result[key] = [];
}
result[key][rowIndex] = resultRow[key];
}
});
rs.pipe(csvConverter);
Here is an example:
TIMESTAMP,UPDATE,UID,BYTES SENT,BYTES RCVED
1395426422,n,10028,1213,5461
1395426422,n,10013,9954,13560
1395426422,n,10109,221391500,141836
1395426422,n,10007,53448,308549
1395426422,n,10022,15506,72125
It will be converted to:
{
"TIMESTAMP": ["1395426422", "1395426422", "1395426422", "1395426422", "1395426422"],
"UPDATE": ["n", "n", "n", "n", "n"],
"UID": ["10028", "10013", "10109", "10007", "10022"],
"BYTES SENT": ["1213", "9954", "221391500", "53448", "15506"],
"BYTES RCVED": ["5461", "13560", "141836", "308549", "72125"]
}
This hook is called when parser received any data from upper stream and allow developers to change it. e.g.
/*
CSV data:
a,b,c,d,e
12,e3,fb,w2,dd
*/
var conv=new Converter();
conv.preProcessRaw=function(data,cb){
//change all 12 to 23
cb(data.replace("12","23"));
}
conv.fromString(csv,function(err,json){
//json:{a:23 ....}
})
By default, the preProcessRaw just returns the data from the source
Converter.prototype.preProcessRaw=function(data,cb){
cb(data);
}
It is also very good to sanitise/prepare the CSV data stream.
var headWhiteSpaceRemoved=false;
conv.preProcessRaw=function(data,cb){
if (!headWhiteSpaceRemoved){
data=data.replace(/^\s+/,"");
cb(data);
}else{
cb(data);
}
}
this hook is called when a file line is emitted. It is called with two parameters fileLineData,lineNumber. The lineNumber is starting from 1.
/*
CSV data:
a,b,c,d,e
12,e3,fb,w2,dd
*/
var conv=new Converter();
conv.preProcessLine=function(line,lineNumber){
//only change 12 to 23 for line 2
if (lineNumber === 2){
line=line.replace("12","23");
}
return line;
}
conv.fromString(csv,function(err,json){
//json:{a:23 ....}
})
Notice that preProcessLine does not support async changes not like preProcessRaw hook.
Following events are used for Converter class:
To subscribe the event:
//Converter Class
var Converter=require("csvtojson").Converter;
//end_parsed will be emitted once parsing finished
csvConverter.on("end_parsed",function(jsonObj){
console.log(jsonObj); //here is your result json object
});
//record_parsed will be emitted each time a row has been parsed.
csvConverter.on("record_parsed",function(resultRow,rawRow,rowIndex){
console.log(resultRow); //here is your result json object
});
There are flags in the library:
*omit*: Omit a column. The values in the column will not be built into JSON result.
*flat*: Mark a head column as is the key of its JSON result.
Example:
*flat*user.name, user.age, *omit*user.gender
Joe , 40, Male
It will be converted to:
[{
"user.name":"Joe",
"user":{
"age":40
}
}]
csvtojson library was designed to accept big csv file converting. To avoid memory consumption, it is recommending to use read stream and write stream.
```js var Converter=require("csvtojson").Converter; var csvConverter=new Converter({constructResult:false}); // The parameter false will turn off final result construction. It can avoid huge memory consumption while parsing. The trade off is final result will not be populated to end_parsed event.
var readStream=require("fs").createReadStream("inputData.csv");
var writeStream=
$ claude mcp add node-csvtojson \
-- python -m otcore.mcp_server <graph>