How to Convert CSV to JSON: A Developer's Guide
CSV is great for spreadsheets and data exports. JSON is the standard for web APIs. Converting between the two is a routine developer task β whether you're loading a spreadsheet into a React component, feeding data to an API, or normalising a database export.
CSV vs JSON: Format Comparison
Here's the same data in both formats:
CSV
name,age,city Alice,28,Jakarta Bob,34,Surabaya Carol,22,Bandung
JSON
[
{"name":"Alice","age":28,"city":"Jakarta"},
{"name":"Bob","age":34,"city":"Surabaya"},
{"name":"Carol","age":22,"city":"Bandung"}
] | Property | CSV | JSON |
|---|---|---|
| Structure | Flat rows and columns | Nested objects and arrays |
| Data types | All values are strings | Strings, numbers, booleans, null, arrays |
| Nesting | Not supported | Supported natively |
| File size | Smaller | Larger (keys repeated per object) |
| Best for | Spreadsheets, exports | APIs, config, web data exchange |
Method 1: Online Tool (Quickest)
Use our CSV to JSON converter to paste or upload a CSV and get formatted JSON output instantly β with options to control key names, data types, and output structure.
- Open the CSV to JSON tool
- Paste your CSV or upload a .csv file
- The first row is used as field names by default
- Click Convert and copy or download the JSON output
Method 2: JavaScript
function csvToJson(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(',');
return headers.reduce((obj, header, i) => {
obj[header] = values[i]?.trim() ?? '';
return obj;
}, {});
});
}
const csv = `name,age,city
Alice,28,Jakarta
Bob,34,Surabaya`;
console.log(JSON.stringify(csvToJson(csv), null, 2)); For production use, prefer a library like Papa Parse β it handles quoted fields, escaped commas, different line endings, and streaming large files.
Method 3: Python
import csv
import json
with open('data.csv', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
data = list(reader)
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
print(f"Converted {len(data)} rows") Python's built-in csv.DictReader uses the header row as dictionary keys automatically β no third-party libraries required.
Handling Common Edge Cases
Commas inside fields
Fields containing commas must be wrapped in double quotes in the CSV: "Smith, John". Most parsers handle this, but naive string splitting will break.
Different delimiters
Some "CSV" files use semicolons (;) or tabs (\t) as delimiters β common in European locales and Excel exports. Specify the delimiter in your parser.
Type conversion
CSV values are always strings. If your JSON needs numbers or booleans, convert them explicitly: parseInt(value) or value === "true".
Missing values
Empty CSV cells become empty strings in JSON. Decide whether to convert them to null or remove the key entirely depending on your use case.
Convert CSV to JSON instantly β free