How to Convert CSV File to JSON in JavaScript?

CSV (Comma-Separated Values) and JSON (JavaScript Object Notation) are two popular data formats. CSV is ideal for tabular data storage, while JSON is widely used in web applications. Converting CSV to JSON in JavaScript is a common requirement when working with data manipulation and API integrations.

Understanding CSV and JSON Formats

CSV Format: Data is stored in rows with values separated by commas. Each row represents a record, and the first row typically contains column headers.

name,age,city
Pankaj,20,Surat
Neeraj,18,Raipur

JSON Format: Data is represented as an array of objects, where each object contains key-value pairs corresponding to the CSV headers and values.

[
  { "name": "Pankaj", "age": "20", "city": "Surat" },
  { "name": "Neeraj", "age": "18", "city": "Raipur" }
]

Using JavaScript Split and Map Methods

This approach uses built-in JavaScript methods to parse CSV data. It's suitable for simple CSV files without complex formatting like quoted values or embedded commas.

Implementation Steps

  • Split the CSV content into lines
  • Extract headers from the first line
  • Map each data row to an object using headers as keys
function csvToJson(csv) {
  const lines = csv.trim().split('<br>');
  const headers = lines[0].split(',');

  return lines.slice(1).map(line => {
    const values = line.split(',');
    return headers.reduce((obj, header, index) => {
      obj[header] = values[index];
      return obj;
    }, {});
  });
}

// Example usage
const csvData = `name,age,city
Pankaj,20,Surat
Neeraj,18,Raipur`;

const jsonResult = csvToJson(csvData);
console.log(JSON.stringify(jsonResult, null, 2));
[
  {
    "name": "Pankaj",
    "age": "20",
    "city": "Surat"
  },
  {
    "name": "Neeraj",
    "age": "18",
    "city": "Raipur"
  }
]

Using Regular Expressions for Complex CSV

For CSV files with quoted values or commas within fields, regular expressions provide better parsing capability. This method handles edge cases that simple string splitting cannot manage.

function csvToJsonWithRegex(csv) {
  const lines = csv.trim().split('<br>');
  const headers = lines[0].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

  return lines.slice(1).map(line => {
    const values = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
    return headers.reduce((obj, header, index) => {
      // Remove surrounding quotes if present
      obj[header] = values[index] ? values[index].replace(/^"|"$/g, '') : '';
      return obj;
    }, {});
  });
}

// Example with quoted values
const complexCsvData = `name,description,city
"John Doe","Software Engineer, Full Stack","New York"
"Jane Smith","Data Scientist","San Francisco"`;

const jsonResult = csvToJsonWithRegex(complexCsvData);
console.log(JSON.stringify(jsonResult, null, 2));
[
  {
    "name": "John Doe",
    "description": "Software Engineer, Full Stack",
    "city": "New York"
  },
  {
    "name": "Jane Smith",
    "description": "Data Scientist",
    "city": "San Francisco"
  }
]

Using External Libraries (PapaParse)

PapaParse is a robust CSV parsing library that handles complex CSV formats, including nested quotes, escaped characters, and large files. It's the recommended approach for production applications.

Installation

npm install papaparse

Implementation

const Papa = require('papaparse');

function parseCsvWithPapa(csv) {
  const result = Papa.parse(csv, { 
    header: true,
    skipEmptyLines: true
  });
  return result.data;
}

// Example usage
const csvData = `name,age,city
Pankaj,20,Surat
Neeraj,18,Raipur`;

const jsonResult = parseCsvWithPapa(csvData);
console.log(JSON.stringify(jsonResult, null, 2));
[
  { "name": "Pankaj", "age": "20", "city": "Surat" },
  { "name": "Neeraj", "age": "18", "city": "Raipur" }
]

Comparison of Methods

Method Complexity Handles Quotes Performance Best For
Split/Map Simple No Fast Basic CSV files
Regular Expressions Medium Yes Medium Moderately complex CSV
PapaParse Simple to use Yes Excellent Production applications

Conclusion

Converting CSV to JSON in JavaScript can be achieved through multiple approaches. Use the split/map method for simple CSV files, regular expressions for moderately complex data, and PapaParse for robust production applications that require handling of complex CSV formats.

Updated on: 2026-03-15T23:19:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements