| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
#CSVTOJSON
Nodejs csv to json converter. Fully featured:
Version 1.1.0 has added new features and optimised lib performance. It also introduced simpler APIs to use. Thus readme is re-written to adapt the preferred new APIs. The lib will support old APIs. To review the old readme please click here.
All changes are backward compatible.
Here is a free online csv to json service ultilising latest csvtojson module.
npm i --save csvtojson
/**
csvStr:
1,2,3
4,5,6
7,8,9
*/
const csv=require('csvtojson')
csv({noheader:true})
.fromString(csvStr)
.on('csv',(csvRow)=>{ // this func will be called 3 times
console.log(csvRow) // => [1,2,3] , [4,5,6] , [7,8,9]
})
.on('done',()=>{
//parsing finished
})/** csv file
a,b,c
1,2,3
4,5,6
*/
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.on('json',(jsonObj)=>{
// combine csv header row and csv line to a json object
// jsonObj.a ==> 1 or 4
})
.on('done',(error)=>{
console.log('end')
})//const csvReadStream -- Readable stream for csv source
const csv=require('csvtojson')
csv()
.fromStream(csvReadStream)
.on('csv',(csvRow)=>{
// csvRow is an array
})
.on('done',(error)=>{
})/**
csvStr:
a,b,c
1,2,3
4,5,6
*/
const csv=require('csvtojson')
csv()
.fromString(csvStr)
.on('csv',(csvRow)=>{ //this func will be called twice. Header row will not be populated
// csvRow => [1,2,3] and [4,5,6]
})
.on('done',()=>{
console.log('end')
})/**
csvStr:
1,2,3
4,5,6
7,8,9
*/
const csv=require('csvtojson')
csv({noheader:true})
.fromString(csvStr)
.on('json',(json)=>{ //this func will be called 3 times
// json.field1 => 1,4,7
// json.field2 => 2,5,8
// json.field3 => 3,6,9
})
.on('done',()=>{
console.log('end')
})$ npm i -g csvtojson
$ csvtojson [options] <csv file path>
Convert csv file and save result to json file:
$ csvtojson source.csv > converted.json
Use multiple cpu-cores:
$ csvtojson --workerNum=4 source.csv > converted.json
Pipe in csv data:
$ cat ./source.csv | csvtojson > converted.json
Print Help:
$ csvtojson
const csv=require('csvtojson')
const converter=csv(params) //params see below Parameters sectionIn above, converter is an instance of Converter which is a subclass of node.js Transform class.
require('csvtojson') returns a constructor function which takes 2 arguments:
const csv=require('csvtojson')
const converter=csv(parserParameters, streamOptions)Both arguments are optional.
For Stream Options please read Stream Option from Node.JS
parserParameters is a JSON object like:
const converter=csv({
noheader:true,
trim:true,
})Following parameters are supported:
All parameters can be used in Command Line tool.
Converter class defined a series of events.
json event is emitted for each parsed CSV line. It passes JSON object and the row number of the CSV line in its callback function.
const csv=require('csvtojson')
csv()
.on('json',(jsonObj, rowIndex)=>{
//jsonObj=> {header1:cell1,header2:cell2}
//rowIndex=> number
})csv event is emitted for each CSV line. It passes an array object which contains cells content of one csv row.
const csv=require('csvtojson')
csv()
.on('csv',(csvRow, rowIndex)=>{
//csvRow=> [cell1, cell2, cell3]
//rowIndex=> number
})csvRow is always an array of strings no matter checkType value.
csv event is the fastest parse event while json and data event is about 2 times slower. Thus if csv is enough, for best performance, just use it without json and data event.
data event is emitted for each parsed CSV line. It passes buffer of strigified JSON unless objectMode is set true in stream option.
const csv=require('csvtojson')
csv()
.on('data',(data)=>{
//data is a buffer object
const jsonStr= data.toString('utf8')
})error event is emitted if there is any errors happened during parsing.
const csv=require('csvtojson')
csv()
.on('error',(err)=>{
console.log(err)
})Note that if error being emitted, the process will stop as node.js will automatically unpipe() upper-stream and chained down-stream1. This will cause end / end_parsed event never being emitted because end event is only emitted when all data being consumed 2.
record_parsed event is emitted for each parsed CSV line. It is combination of json and csv events. For better performance, try to use json and csv instead.
const csv=require('csvtojson')
csv()
.on('record_parsed',(jsonObj, row, index)=>{
})end event is emitted when all CSV lines being parsed.
end_parsed event is emitted when all CSV lines being parsed. The only difference between end_parsed and end events is end_parsed will pass in a JSON array which contains all JSON objects. For better performance, try to use end event instead.
const csv=require('csvtojson')
csv()
.on('end_parsed',(jsonArrObj)=>{
})done event is emitted either after end or error. This indicates the processor has stopped.
const csv=require('csvtojson')
csv()
.on('done',(error)=>{
//do some stuff
})if any error during parsing, it will be passed in callback.
const csv=require('csvtojson')
csv()
.preRawData((csvRawData,cb)=>{
var newData=csvRawData.replace('some value','another value')
cb(newData);
})
.on('json',(jsonObj)=>{
});the function in preRawData will be called directly with the string from upper stream.
const csv=require('csvtojson')
csv()
.preFileLine((fileLineString, lineIdx)=>{
if (lineIdx === 2){
return fileLineString.replace('some value','another value')
}
return fileLineString
})
.on('json',(jsonObj)=>{
});the function is called each time a file line being found in csv stream. the lineIdx is the file line number in the file. The function should return a string to processor.
const csv=require('csvtojson')
csv()
.transf((jsonObj,csvRow,index)=>{
jsonObj.myNewKey='some value'
})
.on('json',(jsonObj)=>{
console.log(jsonObj.myNewKey) // some value
});Transform happens after CSV being parsed before result being emitted or pushed to downstream. This means if jsonObj is changed, the corresponding field in csvRow will not change. Vice versa. The events will emit changed value and downstream will receive changed value.
Transform will cause some performance panelties because it voids optimisation mechanism. Try to use Node.js Transform class as downstream for transformation instead.
One of the powerful feature of csvtojson is the ability to convert csv line to a nested JSON by correctly defining its csv header row. This is default out-of-box feature.
Here is an example. Original CSV:
fieldA.title, fieldA.children.0.name, fieldA.children.0.id,fieldA.children.1.name, fieldA.children.1.employee.0.name,fieldA.children.1.employee.1.name, fieldA.address.0,fieldA.address.1, description
Food Factory, Oscar, 0023, Tikka, Tim, Joe, 3 Lame Road, Grantstown, A fresh new food factory
Kindom Garden, Ceil, 54, Pillow, Amst, Tom, 24 Shaker Street, HelloTown, Awesome castle
The data above contains nested JSON including nested array of JSON objects and plain texts.
Using csvtojson to convert, the result would be like:
[{
"fieldA": {
"title": "Food Factory",
"children": [{
"name": "Oscar",
"id": "0023"
}, {
"name": "Tikka",
"employee": [{
"name": "Tim"
}, {
"name": "Joe"
}]
}],
"address": ["3 Lame Road", "Grantstown"]
},
"description": "A fresh new food factory"
}, {
"fieldA": {
"title": "Kindom Garden",
"children": [{
"name": "Ceil",
"id": "54"
}, {
"name": "Pillow",
"employee": [{
"name": "Amst"
}, {
"name": "Tom"
}]
}],
"address": ["24 Shaker Street", "HelloTown"]
},
"description": "Awesome castle"
}]In case to not produce nested JSON, simply set flatKeys:true in parameters.
/**
csvStr:
a.b,a.c
1,2
*/
csv({flatKeys:true})
.fromString(csvStr)
.on('json',(jsonObj)=>{
//{"a.b":1,"a.c":2} rather than {"a":{"b":1,"c":2}}
});csvtojson uses csv header row as generator of JSON keys. However, it does not require the csv source containing a header row. There are 4 ways to define header rows:
// replace header row (first row) from original source with 'header1, header2'
csv({
noheader: false,
headers: ['header1','header2']
})
// original source has no header row. add 'field1' 'field2' ... 'fieldN' as csv header
csv({
noheader: true
})
// original source has no header row. use 'header1' 'header2' as its header row
csv({
noheader: true
headers: ['header1','header2']
})csvtojson has built-in workers to allow CSV parsing happening on another process and leave Main Process non-blocked. This is very useful when dealing with large csv data on a webserver so that parsing CSV will not block the entire server due to node.js being single threaded.
It is also useful when dealing with tons of CSV data on command line. Multi-CPU core support will dramatically reduce the time needed.
To enable multi-cpu core, simply do:
csv({
workerNum:4 // workerNum>=1
})or in command line:
$ csvtojson --workerNum=4
This will create 3 extra workers. Main process will only be used for delegating data / emitting result / pushing to downstream. Just keep in mind, those operations on Main process are not free and it will still take a certain amount CPU time.
See here for how csvtojson leverages CPU usage when using multi-cores.
There are some limitations when using multi-core feature:
#Change Log
| Back | FazBrowse Home | New Git URL |