How to Convert CSV to JSON in JavaScript

Last updated on December 26, 2022
How to Convert CSV to JSON in JavaScript

You can use the csvtojson library to quickly convert CSV to JSON in JavaScript:

index.js

import csvToJson from 'csvtojson';

const csvFilePath = 'data.csv';

const json = await csvToJson().fromFile(csvFilePath);

const jsonString = JSON.stringify(json, null, 2)

console.log(jsonString);

For a data.csv file like this:

color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2

This will be the resulting JSON:

[
  {
    "color": "red",
    "maxSpeed": "120",
    "age": "2"
  },
  {
    "color": "blue",
    "maxSpeed": "100",
    "age": "3"
  },
  {
    "color": "green",
    "maxSpeed": "130",
    "age": "2"
  }
]

We use csvtojson to convert the CSV into a JSON object, and use the JSON.stringify() method to convert the object into a well-formatted JSON string.

Install csvtojson

Before using csvtojson, you'll need to install it in our project. You can do this with the NPM or Yarn CLI.

npm i csvtojson

# Yarn
yarn add csvtojson

After installation, you'll be able to import it into a JavaScript module, like this:

import csvToJson from 'csvtojson';

// CommonJS
const csvToJson = require('csvtojson');

Convert CSV file to JSON with fromFile()

We call the default export function of the csvtojson module to create the object that will convert the CSV. This object has a bunch of methods, each related in some way to the conversion of CSV to JSON, and fromFile() is one of them.

It accepts the name of the CSV file to convert, and returns a Promise, as the conversion is an asynchronous process. The Promise will resolve with the resulting JSON string.

Convert CSV string to JSON with fromString()

To convert from a CSV data string directly, instead of a file, you can use the also asynchronous fromString() method of the converter object instead:

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const json = await csvToJson().fromString(csv);

const jsonString = JSON.stringify(json, null, 2);

console.log(jsonString);

[
  {
    "First Name": "Russell",
    "Last Name": "Castillo",
    "Age": "23"
  },
  {
    "First Name": "Christy",
    "Last Name": "Harper",
    "Age": "35"
  },
  {
    "First Name": "Eleanor",
    "Last Name": "Mark",
    "Age": "26"
  }
]

Customize conversion of CSV to JSON

The default export function of csvtojson accepts an object used to specify options to customize the conversion process.

One such option is header, an array used to specify the headers in the CSV data.

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
}).fromString(csv);

console.log(json);
[
  {
    "firstName": "Russell",
    "lastName": "Castillo",
    "age": "23"
  },
  {
    "firstName": "Christy",
    "lastName": "Harper",
    "age": "35"
  },
  {
    "firstName": "Eleanor",
    "lastName": "Mark",
    "age": "26"
  }
]

Another is delimeter, used to indicate the character that separates the columns:

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
}).fromString(csv);

const jsonString = JSON.stringify(json, null, 2);

console.log(jsonString);
[
  {
    "firstName": "Russell",
    "lastName": "Castillo",
    "age": "23"
  },
  {
    "firstName": "Christy",
    "lastName": "Harper",
    "age": "35"
  },
  {
    "firstName": "Eleanor",
    "lastName": "Mark",
    "age": "26"
  }
]

We also have ignoreColumns, an option that instructs the converter to ignore certain columns, using a regular expression.

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
  ignoreColumns: /lastName/,
}).fromString(csv);

const jsonString = JSON.stringify(json, null, 2);

console.log(jsonString);
[
  {
    "firstName": "Russell",
    "age": "23"
  },
  {
    "firstName": "Christy",
    "age": "35"
  },
  {
    "firstName": "Eleanor",
    "age": "26"
  }
]

Convert CSV to JSON array of rows

By setting the output option to 'csv', we can produce a list of arrays, where each array represents a row, containing the value of all columns of that row.

For example:

import csvToJson from 'csvtojson';

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;

const json = await csvToJson({
  output: 'csv',
}).fromString(csv);

const jsonString = JSON.stringify(json, null, 2);

console.log(jsonString);
[
  [
    "red",
    "120",
    "2"
  ],
  [
    "blue",
    "100",
    "3"
  ],
  [
    "green",
    "130",
    "2"
  ]
]

Native conversion of CSV to JSON

It's also possible to convert CSV to JSON without using any third-party libraries.

function csvToJson(csv) {
  // \n or \r\n depending on the EOL sequence
  const lines = csv.split('\n');
  const delimeter = ',';

  const result = [];

  const headers = lines[0].split(delimeter);

  for (const line of lines) {
    const obj = {};
    const row = line.split(delimeter);

    for (let i = 0; i < headers.length; i++) {
      const header = headers[i];
      obj[header] = row[i];
    }

    result.push(obj);
  }

  // Prettify output
  return result;
}

const csv = `color,maxSpeed,age
red,120,2
blue,100,3
green,130,2`;

const json = csvToJson(csv);

const jsonString = JSON.stringify(json, null, 2);

console.log(jsonString);

You can modify the code above to allow for varying and more complex CSV data.

Output:

[
  {
    "color": "color",
    "maxSpeed": "maxSpeed",
    "age": "age"
  },
  {
    "color": "red",
    "maxSpeed": "120",
    "age": "2"
  },
  {
    "color": "blue",
    "maxSpeed": "100",
    "age": "3"
  },
  {
    "color": "green",
    "maxSpeed": "130",
    "age": "2"
  }
]
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also