Converting CSV to JSON: A Data Engineering Staple
When to convert CSV to JSON, how to handle headers and delimiters, and how to keep data consistent for APIs and apps.
CSV (Comma Separated Values) is the common export format of spreadsheets and databases. JSON (JavaScript Object Notation) is the common payload format of web APIs. Moving data from one to the other is a routine task for developers.
Why Convert?
CSV is compact and opens in any spreadsheet, but it has no nesting and no types.
- Hierarchy: CSV is flat. JSON supports nested objects and arrays, allowing for richer data representation.
- Types: CSV carries only text. JSON has numbers, booleans and null.
- Web APIs: REST and GraphQL APIs usually consume and return JSON, so a CSV file normally has to be parsed before it can be sent.
The Challenge of Parsing
Writing a regex to split a string by commas seems easy, until you encounter a value like:
1,"Doe, John","San Francisco, CA"Suddenly, a simple split(',') breaks your data. A correct parser, following RFC 4180 (an informational RFC that describes the common CSV format), has to handle:
- Quoted fields containing delimiters
- Quotes escaped by doubling them (
"") - Line breaks inside quoted fields
- Spaces as data: RFC 4180 says spaces are part of the field, so
1, "Doe"is an unquoted field that happens to contain quote characters, not a quoted one
Real files add problems the RFC does not cover, such as different encodings (UTF-8 vs Windows-1252), which are covered below.
CSV Structure Examples
Simple CSV
name,age,city
John,30,New York
Jane,25,San FranciscoConverts to:
[
{"name": "John", "age": "30", "city": "New York"},
{"name": "Jane", "age": "25", "city": "San Francisco"}
]CSV with Quoted Fields
id,name,description
1,"Doe, John","He said ""Hello"""
2,"Smith, Jane","Multi-line
description"Proper parsing requires handling escaped quotes and newlines within quoted fields.
Data Type Conversion
CSV carries only text, but JSON has numbers, booleans and null, so every converter has to decide what to do with a value like 123 or true. Some leave everything as strings. Others infer types, for example turning "123" into 123 and "true" into true. Neither is wrong, but inference has real costs, covered under type conversion traps below.
Real-World Scenarios
Importing Spreadsheet Data
Export data from Excel or Google Sheets as CSV, then convert it to JSON for use in a web application, a seed file or a test fixture.
API Data Transformation
Some APIs and reporting endpoints return CSV while your frontend expects JSON. Parsing it in the browser gives you structured data without a server round trip.
Database Migrations
CSV is a common intermediate format when moving data between systems. Document databases and many import scripts accept JSON, so converting first can simplify the import, as long as you keep IDs and ZIP codes as strings.
Type Conversion Traps
Automatic type detection is convenient and also the most common source of silent data corruption. CSV has no schema, so a converter can only guess from the text. Run the same file through a parser with and without type inference and the difference is obvious:
id,name,zip,active,note
1,Ada,02134,true,
2,"Doe, John",90210,false,"said ""hi"""
// Papa.parse(csv, { header: true })
[{"id":"1","name":"Ada","zip":"02134","active":"true","note":""},
{"id":"2","name":"Doe, John","zip":"90210","active":"false","note":"said \"hi\""}]
// Papa.parse(csv, { header: true, dynamicTyping: true })
[{"id":1,"name":"Ada","zip":2134,"active":true,"note":null},
{"id":2,"name":"Doe, John","zip":90210,"active":false,"note":"said \"hi\""}]The output above comes from PapaParse 5. Look at zip: with type inference, 02134 became the number 2134 and the leading zero is gone for good. Other columns that must stay strings include phone numbers, account numbers, SKUs and anything with significant leading zeros.
- Identifiers are not numbers. If you will never do arithmetic on a column, keep it as a string.
- Large integers lose precision. JavaScript numbers are 64-bit floats, so
Number("12345678901234567890")gives12345678901234567000. Keep long IDs as strings. - Number() is more permissive than you expect.
Number("")is0,Number("1e3")is1000, andNumber("0x1F")is31. Validate with a pattern before coercing. - Boolean rules vary by converter. PapaParse's
dynamicTypingconvertstrueandTRUEbut leavesTrue,yesandnullas strings. Normalise your source data or map those values explicitly. - Empty cells are ambiguous. Decide whether an empty cell means
"",null, or a missing key, and apply that rule consistently.
Headers, Delimiters and Encoding
Header Problems
Object keys come from the header row, so header quality decides JSON quality. Duplicate headers collide: PapaParse renames the second a in a,a to a_1, whereas a naive converter would overwrite the first value. Headers with spaces or punctuation are legal JSON keys but awkward to use as row.first name, so many teams normalise them to camelCase or snake_case during conversion. Also remember that not every file has a header row: if the first row is data, it will silently become your keys. See our naming conventions guide for choosing one.
Delimiters
RFC 4180 describes comma-separated files, but real exports often use semicolons or tabs. Some locales use the comma as the decimal separator, which makes spreadsheet software default to semicolons. Auto-detection works on clean files but can fail on short ones (PapaParse reports UndetectableDelimiter), so in your own code pass the delimiter explicitly when you know it. Our converter relies on auto-detection and has no delimiter setting, so a file it misreads needs its delimiter normalised first.
The Invisible BOM
Excel's "CSV UTF-8" export prepends a byte order mark (U+FEFF). If your parser does not strip it, the first header becomes "\uFEFFid", which looks identical to "id" but is three characters long, so row.id is undefined. PapaParse removes it for you. With a hand-rolled parser, strip it first with text.replace(/^\uFEFF/, "").
Ragged and Blank Rows
Real files contain blank lines and rows with the wrong number of fields. A row with too many fields has no header for the extras, and a row with too few leaves keys missing. Skip empty lines, and surface the parser's error list rather than ignoring it: PapaParse reports codes such as TooManyFields and TooFewFields with row numbers.
Building Nested JSON From a Flat Table
CSV cannot nest, but a header convention can encode it. A common approach is dot notation, where address.city means a city key inside an address object. The conversion is a few lines:
const rows = Papa.parse(csv, { header: true }).data.map((r) => {
const out = {};
for (const [k, v] of Object.entries(r)) {
const parts = k.split(".");
let o = out;
parts.slice(0, -1).forEach((p) => (o = o[p] ??= {}));
o[parts.at(-1)] = v;
}
return out;
});
// id,name,address.city,address.zip
// 1,Ada,Pune,411001
// 2,Bob,Leeds,LS1
JSON.stringify(rows)
// [{"id":"1","name":"Ada","address":{"city":"Pune","zip":"411001"}},
// {"id":"2","name":"Bob","address":{"city":"Leeds","zip":"LS1"}}]For repeated values (tags, phone numbers) pick a separator inside the cell, such as red|blue, and split it after parsing. Going the other direction, nested JSON must be flattened with the same convention before conversion. The JSON to CSV converter does not flatten for you: PapaParse writes a nested object as [object Object], so flatten first.
Choosing the JSON Output Shape
- Array of objects (the default): self-describing and easy to consume, but each row repeats every key, so it is larger than the CSV.
- Array of arrays: keeps the header as the first row and is the most compact, at the cost of readability.
- Newline-delimited JSON: one object per line, ideal for streaming and for loading into tools that read line by line.
Repeated keys are exactly what token-oriented formats target. If the JSON is headed to a language model, compare sizes with the JSON to TOON converter and read TOON vs JSON.
Security and Performance
- Treat uploaded CSV as untrusted. Parse it as data, never evaluate it, and cap file size and row count in server-side code.
- Formula injection: if converted data later flows back into a spreadsheet, cells starting with
=,+,-or@can run as formulas. Escape or prefix them on export. - Big files: parse in a streaming or chunked mode, or in a Web Worker, so the browser tab does not freeze. Building one huge string with
JSON.stringifyneeds memory for both the parsed rows and the output, so write output incrementally when you can. - Privacy: client-side conversion means the file never leaves the device, which matters for customer exports. See why privacy-first tools matter.
Using the Converter
Instead of writing your own fragile parser, use a real one. Our CSV to JSON Converter parses with PapaParse, uses the first row as object keys, skips blank lines, and stops with the first parse error it finds. Every value stays a string (no type inference), the delimiter is auto-detected, and you can copy or download the result. Because it runs in your browser, the file is not uploaded anywhere.
Need to go the other way? The JSON to CSV Converter turns a JSON array of objects into CSV for spreadsheets and reports.
Frequently Asked Questions
How do I convert CSV to JSON in JavaScript?
Use a real CSV parser such as PapaParse with header: true, which returns an array of objects keyed by the header row. Avoid split(","), which breaks on quoted fields, escaped quotes and embedded newlines.
Why are all my JSON values strings?
CSV stores only text, so a parser returns strings unless you turn on type inference or convert columns yourself. Convert only the columns you know are numeric or boolean, to avoid damaging IDs and ZIP codes.
Why does my first column name look wrong or undefined?
The file probably begins with a byte order mark. It is invisible, but it becomes part of the first header. Strip it before parsing, or use a parser that does so automatically.
Can CSV represent nested data?
Not natively. You can encode nesting with conventions like dotted headers or delimited cell values, but both sides must agree on the convention. If the data is genuinely hierarchical, JSON or XML is a better fit.
Written by Kashyap Thakar
Spotted a mistake? Let me know