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.
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"}]
How to Convert CSV to JSON in JavaScript ?
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:
Table of Content
- Splitting Lines and Looping
- Using Regular Expression
- Using External Libraries