A tool concentrating on converting csv data to JSON with customised parser supporting
Last updated a year ago by keyang .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install csvtojson 
SYNC missed versions from official npm registry.

Build Status Coverage Status OpenCollective OpenCollective


csvtojson module is a comprehensive nodejs csv parser to convert csv to json or column arrays. It can be used as node.js library / command line tool / or in browser. Below are some features:

  • Strictly follow CSV definition RF4180
  • Work with millions of lines of CSV data
  • Provide comprehensive parsing parameters
  • Provide out of box CSV parsing tool for Command Line
  • Blazing fast -- Focus on performance
  • Give flexibility to developer with 'pre-defined' helpers
  • Allow async / streaming parsing
  • Provide a csv parser for both Node.JS and browsers
  • Easy to use API

csvtojson online

Here is a free online csv to json convert service utilizing latest csvtojson module.

Upgrade to V2

csvtojson has released version 2.0.0.

It is still able to use v1 with csvtojson@2.0.0

// v1
const csvtojsonV1=require("csvtojson/v1");
// v2
const csvtojsonV2=require("csvtojson");
const csvtojsonV2=require("csvtojson/v2");


Quick Start



npm i --save csvtojson

From CSV File to JSON Array

/** csv file
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
	 * [
	 * 	{a:"1", b:"2", c:"3"},
	 * 	{a:"4", b:"5". c:"6"}
	 * ]

// Async / await usage
const jsonArray=await csv().fromFile(csvFilePath);

From CSV String to CSV Row

const csv=require('csvtojson')
	output: "csv"
	console.log(csvRow) // => [["1","2","3"], ["4","5","6"], ["7","8","9"]]

Asynchronously process each line from csv url

const request=require('request')
const csv=require('csvtojson')

	return new Promise((resolve,reject)=>{
		// long operation for each json e.g. transform / write into database.

Convert to CSV lines


const csv=require('csvtojson')
	// csvLine =>  "1,2,3" and "4,5,6"

Use Stream

const csv=require('csvtojson');

const readStream=require('fs').createReadStream(csvFilePath);

const writeStream=request.put('http://mysite.com/obj.json');


To find more detailed usage, please see API section

Command Line Usage


$ npm i -g csvtojson


$ csvtojson [options] <csv file path>


Convert csv file and save result to json file:

$ csvtojson source.csv > converted.json

Pipe in csv data:

$ cat ./source.csv | csvtojson > converted.json

Print Help:

$ csvtojson



require('csvtojson') returns a constructor function which takes 2 arguments:

  1. Parser parameters
  2. Stream options
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({

Following parameters are supported:

  • output: The format to be converted to. "json" (default) -- convert csv to json. "csv" -- convert csv to csv row array. "line" -- convert csv to csv line string
  • delimiter: delimiter used for separating columns. Use "auto" if delimiter is unknown in advance, in this case, delimiter will be auto-detected (by best attempt). Use an array to give a list of potential delimiters e.g. [",","|","$"]. default: ","
  • quote: If a column contains delimiter, it is able to use quote character to surround the column content. e.g. "hello, world" won't be split into two columns while parsing. Set to "off" will ignore all quotes. default: " (double quote)
  • trim: Indicate if parser trim off spaces surrounding column content. e.g. " content " will be trimmed to "content". Default: true
  • checkType: This parameter turns on and off whether check field type. Default is false. (The default is true if version < 1.1.4)
  • ignoreEmpty: Ignore the empty value in CSV columns. If a column value is not given, set this to true to skip them. Default: false.
  • fork (experimental): Fork another process to parse the CSV stream. It is effective if many concurrent parsing sessions for large csv files. Default: false
  • noheader:Indicating csv data has no header row and first row is data row. Default is false. See header row
  • headers: An array to specify the headers of CSV data. If --noheader is false, this value will override CSV header row. Default: null. Example: ["my field","name"]. See header row
  • flatKeys: Don't interpret dots (.) and square brackets in header fields as nested object or array identifiers at all (treat them like regular characters for JSON field identifiers). Default: false.
  • maxRowLength: the max character a csv row could have. 0 means infinite. If max number exceeded, parser will emit "error" of "row_exceed". if a possibly corrupted csv data provided, give it a number like 65535 so the parser won't consume memory. default: 0
  • checkColumn: whether check column number of a row is the same as headers. If column number mismatched headers number, an error of "mismatched_column" will be emitted.. default: false
  • eol: End of line character. If omitted, parser will attempt to retrieve it from the first chunks of CSV data.
  • escape: escape character used in quoted column. Default is double quote (") according to RFC4108. Change to back slash (\) or other chars for your own case.
  • includeColumns: This parameter instructs the parser to include only those columns as specified by the regular expression. Example: /(name|age)/ will parse and include columns whose header contains "name" or "age"
  • ignoreColumns: This parameter instructs the parser to ignore columns as specified by the regular expression. Example: /(name|age)/ will ignore columns whose header contains "name" or "age"
  • colParser: Allows override parsing logic for a specific column. It accepts a JSON object with fields like: headName: <String | Function | ColParser> . e.g. {field1:'number'} will use built-in number parser to convert value of the field1 column to number. For more information See details below
  • alwaysSplitAtEOL: Always interpret each line (as defined by eol like \n) as a row. This will prevent eol characters from being used within a row (even inside a quoted field). Default is false. Change to true if you are confident no inline line breaks (like line break in a cell which has multi line text).
  • nullObject: How to parse if a csv cell contains "null". Default false will keep "null" as string. Change to true if a null object is needed.
  • downstreamFormat: Option to set what JSON array format is needed by downstream. "line" is also called ndjson format. This format will write lines of JSON (without square brackets and commas) to downstream. "array" will write complete JSON array string to downstream (suitable for file writable stream etc). Default "line"
  • needEmitAll: Parser will build JSON result is .then is called (or await is used). If this is not desired, set this to false. Default is true. All parameters can be used in Command Line tool.

Asynchronous Result Process

Since v2.0.0, asynchronous processing has been fully supported.

e.g. Process each JSON result asynchronously.

	return new Promise((resolve,reject)=>{
		// Async operation on the json
		// don't forget to call resolve and reject

For more details please read:


Converter class defined a series of events.


header event is emitted for each CSV file once. It passes an array object which contains the names of the header row.

const csv=require('csvtojson')
	//header=> [header1, header2, header3]

header is always an array of strings without types.


data event is emitted for each parsed CSV line. It passes buffer of stringified JSON in ndjson format unless objectMode is set true in stream option.

const csv=require('csvtojson')
	//data is a buffer object
	const jsonStr= data.toString('utf8')


error event is emitted if any errors happened during parsing.

const csv=require('csvtojson')

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 event never being emitted because end event is only emitted when all data being consumed 2. If need to know when parsing finished, use done event instead of end.

  1. Node.JS Readable Stream
  2. Writable end Event


done event is emitted either after parsing successfully finished or any error happens. This indicates the processor has stopped.

const csv=require('csvtojson')
	//do some stuff

if any error during parsing, it will be passed in callback.

Hook & Transform

Raw CSV Data Hook

the hook -- preRawData will be called with csv string passed to parser.

const csv=require('csvtojson')
// synchronouse
	var newData=csvRawData.replace('some value','another value');
	return newData;

// asynchronous
	return new Promise((resolve,reject)=>{
		var newData=csvRawData.replace('some value','another value');

CSV File Line Hook

The function is called each time a file line has been parsed in csv stream. The lineIdx is the file line number in the file starting with 0.

const csv=require('csvtojson')
// synchronouse
.preFileLine((fileLineString, lineIdx)=>{
	if (lineIdx === 2){
		return fileLineString.replace('some value','another value')
	return fileLineString

// asynchronous
.preFileLine((fileLineString, lineIdx)=>{
	return new Promise((resolve,reject)=>{
			// async function processing the data.

Result transform

To transform result that is sent to downstream, use .subscribe method for each json populated.

const csv=require('csvtojson')
	jsonObj.myNewKey='some value'
	// OR asynchronously
	return new Promise((resolve,reject)=>{
		jsonObj.myNewKey='some value';
	console.log(jsonObj.myNewKey) // some value

Nested JSON Structure

csvtojson is able 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"

Flat Keys

In order to not produce nested JSON, simply set flatKeys:true in parameters.

	//{"a.b":1,"a.c":2}  rather than  {"a":{"b":1,"c":2}}

Header Row

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:

  1. First row of csv source. Use first row of csv source as header row. This is default.
  2. If first row of csv source is header row but it is incorrect and need to be replaced. Use headers:[] and noheader:false parameters.
  3. If original csv source has no header row but the header definition can be defined. Use headers:[] and noheader:true parameters.
  4. If original csv source has no header row and the header definition is unknown. Use noheader:true. This will automatically add fieldN header to csv cells


// replace header row (first row) from original source with 'header1, header2'
	noheader: false,
	headers: ['header1','header2']

// original source has no header row. add 'field1' 'field2' ... 'fieldN' as csv header
	noheader: true

// original source has no header row. use 'header1' 'header2' as its header row
	noheader: true,
	headers: ['header1','header2']

Column Parser

Column Parser allows writing a custom parser for a column in CSV data.

What is Column Parser

When csvtojson walks through csv data, it converts value in a cell to something else. For example, if checkType is true, csvtojson will attempt to find a proper type parser according to the cell value. That is, if cell value is "5", a numberParser will be used and all value under that column will use the numberParser to transform data.

Built-in parsers

There are currently following built-in parser:

  • string: Convert value to string
  • number: Convert value to number
  • omit: omit the whole column

This will override types infered from checkType:true parameter. More built-in parsers will be added as requested in issues page.


/*csv string
	//jsonObj: {column2:"1234"}

Custom parsers function

Sometimes, developers want to define custom parser. It is able to pass a function to specific column in colParser.


/*csv data
name, birthday
Joe, 1970-01-01
		"birthday":function(item, head, resultRow, row , colIdx){
				item - "1970-01-01"
				head - "birthday"
				resultRow - {name:"Joe"}
				row - ["Joe","1970-01-01"]
				colIdx - 1
			return new Date(item);

Above example will convert birthday column into a js Date object.

The returned value will be used in result JSON object. Returning undefined will not change result JSON object.

Flat key column

It is also able to mark a column as flat:

/*csv string
			cellParser: "number" // string or a function 
	//jsonObj: {"person.number":1234,"person":{"comment":"hello"}}


Very much appreciate any types of donation and support.


csvtojson follows github convention for contributions. Here are some steps:

  1. Fork the repo to your github account
  2. Checkout code from your github repo to your local machine.
  3. Make code changes and don't forget add related tests.
  4. Run npm test locally before pushing code back.
  5. Create a Pull Request on github.
  6. Code review and merge
  7. Changes will be published to NPM within next version.

Thanks all the contributors


Thank you to all our backers! [Become a backer]



Thank you to all our sponsors! (please ask your company to also support this open source project by becoming a sponsor)



Browser Usage

To use csvtojson in browser is quite simple. There are two ways:

1. Embed script directly into script tag

There is a pre-built script located in browser/csvtojson.min.js. Simply include that file in a script tag in index.html page:

<script src="node_modules/csvtojson/browser/csvtojson.min.js"></script>
<!-- or use cdn -->
<script src="https://cdn.rawgit.com/Keyang/node-csvtojson/d41f44aa/browser/csvtojson.min.js"></script>

then use a global csv function

	output: "csv"


2. Use webpack or browserify

If a module packager is preferred, just simply require("csvtojson"):

var csv=require("csvtojson");

// or with import
import * as csv from "csvtojson";

//then use csv as normal

Current Tags

  • 2.0.10                                ...           latest (a year ago)

82 Versions

  • 2.0.10                                ...           a year ago
  • 2.0.8                                ...           2 years ago
  • 2.0.7                                ...           2 years ago
  • 2.0.6                                ...           2 years ago
  • 2.0.4                                ...           2 years ago
  • 2.0.3                                ...           2 years ago
  • 2.0.2                                ...           2 years ago
  • 2.0.1                                ...           2 years ago
  • 2.0.0                                ...           2 years ago
  • 1.1.12                                ...           2 years ago
  • 1.1.11                                ...           2 years ago
  • 1.1.9                                ...           3 years ago
  • 1.1.8                                ...           3 years ago
  • 1.1.7                                ...           3 years ago
  • 1.1.6                                ...           3 years ago
  • 1.1.5                                ...           3 years ago
  • 1.1.4                                ...           3 years ago
  • 1.1.3                                ...           3 years ago
  • 1.1.2                                ...           3 years ago
  • 1.1.1                                ...           4 years ago
  • 1.1.0                                ...           4 years ago
  • 1.0.3                                ...           4 years ago
  • 1.0.2                                ...           4 years ago
  • 1.0.1                                ...           4 years ago
  • 1.0.0                                ...           4 years ago
  • 0.5.14                                ...           4 years ago
  • 0.5.13                                ...           4 years ago
  • 0.5.12                                ...           4 years ago
  • 0.5.11                                ...           4 years ago
  • 0.5.10                                ...           4 years ago
  • 0.5.9                                ...           4 years ago
  • 0.5.8                                ...           4 years ago
  • 0.5.7                                ...           4 years ago
  • 0.5.6                                ...           4 years ago
  • 0.5.5                                ...           4 years ago
  • 0.5.4                                ...           4 years ago
  • 0.5.3                                ...           4 years ago
  • 0.5.2                                ...           4 years ago
  • 0.5.1                                ...           4 years ago
  • 0.5.0                                ...           5 years ago
  • 0.4.8                                ...           5 years ago
  • 0.4.7                                ...           5 years ago
  • 0.4.6                                ...           5 years ago
  • 0.4.5                                ...           5 years ago
  • 0.4.4                                ...           5 years ago
  • 0.4.3                                ...           5 years ago
  • 0.4.2                                ...           5 years ago
  • 0.4.1                                ...           5 years ago
  • 0.4.0                                ...           5 years ago
  • 0.3.21                                ...           5 years ago
  • 0.3.20                                ...           5 years ago
  • 0.3.19                                ...           5 years ago
  • 0.3.18                                ...           5 years ago
  • 0.3.17                                ...           6 years ago
  • 0.3.16                                ...           6 years ago
  • 0.3.15                                ...           6 years ago
  • 0.3.14                                ...           6 years ago
  • 0.3.13                                ...           6 years ago
  • 0.3.12                                ...           6 years ago
  • 0.3.11                                ...           6 years ago
  • 0.3.10                                ...           6 years ago
  • 0.3.9                                ...           6 years ago
  • 0.3.8                                ...           6 years ago
  • 0.3.7                                ...           6 years ago
  • 0.3.6                                ...           6 years ago
  • 0.3.5                                ...           6 years ago
  • 0.3.4                                ...           6 years ago
  • 0.3.3                                ...           6 years ago
  • 0.3.2                                ...           6 years ago
  • 0.3.1                                ...           6 years ago
  • 0.3.0                                ...           6 years ago
  • 0.2.2                                ...           6 years ago
  • 0.2.1                                ...           6 years ago
  • 0.2.0                                ...           6 years ago
  • 0.1.7                                ...           6 years ago
  • 0.1.6                                ...           6 years ago
  • 0.1.5                                ...           7 years ago
  • 0.1.4                                ...           7 years ago
  • 0.1.3                                ...           7 years ago
  • 0.1.2                                ...           7 years ago
  • 0.1.1                                ...           7 years ago
  • 0.1.0                                ...           7 years ago
Maintainers (1)
Today 1
This Week 211
This Month 111
Last Day 71
Last Week 307
Last Month 1,828
Dependencies (3)
Dev Dependencies (14)
Dependents (497)

Copyright 2014 - 2016 © taobao.org |