Parse CSV String
Convert a CSV string to an array of objects.
Code
JavaScript
function csvToJson(csv) {
const lines = csv.trim().split("\n");
const headers = lines[0].split(",");
return lines.slice(1).map((line) => {
const values = line.split(",");
return headers.reduce((obj, h, i) => {
obj[h.trim()] = values[i]?.trim() ?? "";
return obj;
}, {});
});
}
const csv = "name,age\nAlice,30\nBob,25";
console.log(csvToJson(csv));Line-by-line explanation
- 1.Split by newline, first line is headers.
- 2.Split each line by comma.
- 3.Reduce to build object with header keys.
- 4.Note: doesn't handle quoted commas.
Expected output
[{ name: "Alice", age: "30" }, { name: "Bob", age: "25" }]