The Wayback Machine - https://web.archive.org/web/20240621203608/https://www.geeksforgeeks.org/how-to-convert-csv-to-json-in-javascript/
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



Similar Reads

How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Content Using String ManipulationUsing csvjson library
3 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Convert JSON file into CSV in PHP ?
In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Separated Value) files represent data in a tabular for
2 min read
How to Convert CSV to JSON in ReactJS ?
Dealing with data in various formats is a common task in web development. CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are two widely used formats for storing and transmitting data. Converting CSV to JSON is often required when working with data in ReactJS applications. ApproachBegin by creating a new React application using t
4 min read
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
A CSV is a comma-separated value file, identified by the .csv extension, is a format used for tabular data storage where values are separated by commas. This article presents a method to convert CSV data to JavaScript Object Notation (JSON) without any relaying on third-party npm packages. Unlike typical conversions, this approach handles scenarios
4 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
Difference Between JSON and CSV
JSON: JSON refers to JavaScript Object Notation. It is a language-independent, human-readable language used for its simplicity and is most commonly used in web-based applications. The JSON extensions end with a .json. JSON is a user-friendly substitute for XML as it is lightweight and easy to read. It supports data structures like array and objects
2 min read