Open In App

How to Convert CSV to JSON in JavaScript ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We’ll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in JavaScript which are as follows:

Splitting Lines and Looping

This approach simplifies CSV parsing in JavaScript by manually processing each line of the CSV data and constructing the JSON structure. It involves splitting the CSV text into lines and then splitting each line into individual values using commas as separators. By iterating through each line, excluding the header, we create a JSON object, with the first line’s values serving as keys and the subsequent lines’ values as the corresponding data.

Example: Converting CSV to JSON in JavaScript: Parsing a CSV string into JSON data, mapping headers to keys, and values to corresponding data fields, producing structured JSON output.

JavaScript
function csvToJson(csvString) {
    const rows = csvString
        .split("\n");

    const headers = rows[0]
        .split(",");

    const jsonData = [];
    for (let i = 1; i < rows.length; i++) {

        const values = rows[i]
            .split(",");

        const obj = {};

        for (let j = 0; j < headers.length; j++) {

            const key = headers[j]
                .trim();
            const value = values[j]
                .trim();

            obj[key] = value;
        }

        jsonData.push(obj);
    }
    return JSON.stringify(jsonData);
}
const csvData = "name,age,city\nAlice,30,New York\nBob,25,London";
const jsonData = csvToJson(csvData);
console.log(jsonData); 

Output
[{"name":"Alice","age":"30","city":"New York"},{"name":"Bob","age":"25","city":"London"}]

Using Regular Expression

This advanced approach uses regular expressions to handle complex CSV parsing cases, including special characters, commas within values, and intricate splitting requirements. Regular expressions act as detectives, identifying specific patterns within the CSV data, such as commas, quoted values, and escapes, enabling precise extraction of individual values.

Example: Converting CSV to JSON Using Regular Expressions: A Comprehensive Example

JavaScript
function csvToJsonRegex(csvString) {
    const regex = /,(?=(?:[^"]*"[^"]*")*(?![^"]*"))/;
    const rows = csvString
        .split("\n");
    const headers = rows[0]
        .split(regex);
    const jsonData = [];

    for (let i = 1; i < rows.length; i++) {
        const values = rows[i]
            .split(regex);
        const obj = {};
        for (let j = 0; j < headers.length; j++) {
            obj[headers[j]
                .trim()] = values[j]
                    .trim();
        }
        jsonData.push(obj);
    }

    return JSON.stringify(jsonData);
}
const csvData = "name,age,city\nAlice,30,New York\nBob,25,London";
const jsonData = csvToJsonRegex(csvData);
console.log(jsonData);

Output
[{"name":"Alice","age":"30","city":"New York"},{"name":"Bob","age":"25","city":"London"}]

Using External Libraries

This method harnesses external libraries like Papa Parse to simplify CSV conversion with pre-built tools. These libraries specialize in efficient parsing, handling various delimiters, quotations, and errors. They streamline the process, offering additional features like data type conversion.

Syntax to run:

npm i papaparse

Example: To demonstrate converting the csv file to JSON in JavaScript using the papa parse external library.

JavaScript
const Papa = require("papaparse");

const csvData = "name,age,city\nAlice,30,New York\nBob,25,London";

Papa.parse(csvData, {
  header: true,
  complete: function(results) {
    console.log(results.data); 
  },
});

Output:

Screenshot-2024-04-08-182513

output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads