CSV Rows as JSON Objects
Convert each CSV row into a self-contained JSON object with named properties. Learn the mapping logic, edge cases, and when to use objects vs arrays.
Detailed Explanation
Mapping CSV Rows to JSON Objects
When converting CSV to JSON, you typically want each row to become a JSON object where the keys come from the header and the values from the respective columns. This is the most common and useful output format.
The mapping logic
Given a CSV with n columns and m data rows, the result is an array of m objects, each with n properties:
id,name,role,active
1,Alice,admin,true
2,Bob,editor,false
3,Carol,viewer,true
[
{ "id": "1", "name": "Alice", "role": "admin", "active": "true" },
{ "id": "2", "name": "Bob", "role": "editor", "active": "false" },
{ "id": "3", "name": "Carol", "role": "viewer", "active": "true" }
]
Implementation in JavaScript
function csvToJsonObjects(csv) {
const lines = csv.trim().split("\n");
const headers = lines[0].split(",").map(h => h.trim());
return lines.slice(1).map(line => {
const values = line.split(",");
const obj = {};
headers.forEach((key, i) => {
obj[key] = values[i]?.trim() ?? "";
});
return obj;
});
}
Objects vs arrays of arrays
There are two common JSON output formats for CSV data:
| Format | Pros | Cons |
|---|---|---|
| Array of objects | Self-documenting, easy to query by key | Larger output, repeated key names |
| Array of arrays | Compact, preserves column order | Requires separate header metadata |
Choose objects when the JSON will be consumed by APIs, stored in document databases, or processed by code that accesses fields by name. Choose arrays when file size matters and consumers already know the schema.
Edge cases
- Rows shorter than the header: Missing values should default to
""ornull. - Rows longer than the header: Extra values are typically discarded, but some parsers include them under generated keys.
- Completely empty rows: Skip them entirely to avoid empty objects in the output.
Use Case
Building a data import feature for a CRM application where users upload CSV contact lists and the backend processes each row as an individual contact JSON object.