Tabular data formats like CSV are great for storing rows, but modern web applications and APIs interact using JSON (JavaScript Object Notation). Converting flat CSV files into structured JSON array objects is a common task for developers. This guide covers how to perform this conversion client-side in the browser.
Why Convert CSV to JSON?
CSV structures represent two-dimensional tables, whereas JSON represents rich hierarchical structures. Converting tables to JSON provides several advantages:
- API Compatibility: Almost all modern REST APIs and databases (like MongoDB) expect payloads in JSON format.
- Nested Support: JSON can represent nested arrays and complex relationships, whereas CSV is flat.
- Client Processing: Web frontends can directly iterate over and access JSON keys without manually parsing commas or headers.
Parsing CSV to JSON in JavaScript
To convert CSV to JSON client-side, we must split the input text by lines, extract the header titles from the first row, and map the values of the subsequent rows to matching object keys.
Step-by-Step JS Implementation
Here is a lightweight, pure JavaScript function to parse a CSV string into a JSON array of objects:
function csvToJson(csvText) {
const lines = csvText.trim().split(/\r?\n/);
if (lines.length === 0) return [];
// Extract and clean header keys
const headers = lines[0].split(',').map(header => header.trim());
const jsonArray = [];
for (let i = 1; i < lines.length; i++) {
const currentLine = lines[i].split(',');
// Skip empty rows
if (currentLine.length !== headers.length) continue;
const rowObj = {};
for (let j = 0; j < headers.length; j++) {
rowObj[headers[j]] = currentLine[j].trim();
}
jsonArray.push(rowObj);
}
return jsonArray;
}
// Example usage
const csv = "id,name,role\n101,Alice,Developer\n102,Bob,Designer";
const json = csvToJson(csv);
console.log(JSON.stringify(json, null, 2));
Convert CSV to JSON Instantly with Sylvaera
If you have large files or need advanced options (like handling comma values inside quotes), you can use Sylvaera's free CSV to JSON converter. It processes all conversion calculations in your browser, maintaining full security for your datasets.