CSV to JSON Converter — Transform Spreadsheet Data to JSON
CSV to JSON conversion turns rows and columns into an array of objects, using the header row as keys. Here's how the conversion works, edge cases to handle, and how to do it in...
CSV to JSON conversion maps each row in a CSV file to a JSON object, using the header row as the object keys. A CSV with 100 rows and 5 columns becomes a JSON array of 100 objects, each with 5 properties.
Use the CSV to JSON converter to paste CSV data and get formatted JSON instantly.
What the conversion looks like
CSV input:
name,age,city,active
Alice,30,New York,true
Bob,25,London,false
Carol,35,Tokyo,true
JSON output:
[
{"name": "Alice", "age": "30", "city": "New York", "active": "true"},
{"name": "Bob", "age": "25", "city": "London", "active": "false"},
{"name": "Carol", "age": "35", "city": "Tokyo", "active": "true"}
]
All values are strings by default. Type coercion (converting "30" to 30 as a number) requires additional handling.
Type coercion in CSV to JSON
CSV has no type system — every cell is a string. When converting to JSON, you often want numeric columns to be numbers and boolean columns to be actual booleans.
Without coercion (default):
{"name": "Alice", "age": "30", "active": "true"}
With coercion:
{"name": "Alice", "age": 30, "active": true}
Most converters offer a “type coercion” or “infer types” option. The logic:
- If the value matches
true/false(case-insensitive) → boolean - If
parseFloat(value)returns a valid number andString(parseFloat(value)) === value→ number - Otherwise → string
Handling edge cases in CSV
Quoted fields with commas
CSV standard (RFC 4180) allows fields to contain the delimiter character if the field is quoted:
name,address,city
Alice,"123 Main St, Apt 4",New York
"123 Main St, Apt 4" is one field despite containing a comma. A CSV parser handles this; a naive split(',') would break it.
Quoted fields with newlines
A field can contain newlines if quoted:
name,notes
Alice,"Line one
Line two"
This is valid CSV. The record spans two text lines but is one CSV row.
Escaped quotes
A double quote inside a quoted field is escaped as "":
quote,"He said ""hello""",end
Parses to: { quote: 'He said "hello"' }.
Different delimiters
CSV technically means “comma-separated,” but many spreadsheet exports use tabs (TSV — tab-separated values) or semicolons (common in European locales where the comma is the decimal separator).
The CSV to JSON converter handles comma, tab, and semicolon separators.
How to convert CSV to JSON in code
JavaScript (Papa Parse — recommended)
import Papa from 'papaparse';
const csv = `name,age,city
Alice,30,New York
Bob,25,London`;
const result = Papa.parse(csv, {
header: true, // Use first row as keys
dynamicTyping: true, // Auto-convert numbers and booleans
skipEmptyLines: true
});
console.log(result.data);
// [
// { name: 'Alice', age: 30, city: 'New York' },
// { name: 'Bob', age: 25, city: 'London' }
// ]
Papa Parse handles all CSV edge cases (quoted fields, escaped quotes, multiple delimiter types).
JavaScript (manual, simple case)
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 Object.fromEntries(
headers.map((header, i) => [header.trim(), values[i]?.trim()])
);
});
}
// WARNING: This breaks on commas inside quoted fields
// Use Papa Parse for production code
Python
import csv
import json
# From a file:
with open('data.csv', 'r', newline='') as f:
reader = csv.DictReader(f)
data = list(reader)
print(json.dumps(data, indent=2))
# From a string:
import io
csv_text = """name,age,city
Alice,30,New York
Bob,25,London"""
reader = csv.DictReader(io.StringIO(csv_text))
data = list(reader)
print(json.dumps(data, indent=2))
Python’s csv.DictReader uses the first row as keys and handles all RFC 4180 edge cases.
Command line (csvkit)
# Install:
pip install csvkit
# Convert:
csvjson data.csv > data.json
# With indentation:
csvjson --indent 2 data.csv
# Filter columns:
csvjson --columns name,age data.csv
jq approach (when you already have the CSV as lines)
# Simple CSV to JSON with awk + jq:
awk -F',' 'NR==1{split($0,h,",")} NR>1{for(i=1;i<=NF;i++) printf "%s%s",h[i]"="$i,(i==NF?"\n":",")}' data.csv | \
jq -Rs 'split("\n")'
For complex CSV, csvkit or Python is more reliable.
Nested JSON from flat CSV
CSV is inherently flat (two dimensions: rows and columns). JSON can be nested. Some converters support dot notation in headers to create nested JSON:
name,address.street,address.city,address.zip
Alice,123 Main St,New York,10001
Converts to:
[{
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}]
This is a convention, not a CSV standard. The CSV to JSON converter supports this dot-notation expansion.
Common conversion mistakes
Not handling the header row: Treating the header as data produces a first object like {"name": "name", "age": "age"}. Most converters use the first row as headers by default.
Ignoring quoted fields: Splitting on commas breaks when fields contain commas. Use a proper CSV parser.
Losing type information: All-string JSON may break downstream code expecting numbers. Enable type coercion if the consumer expects typed values.
Encoding issues: CSV files from Excel may be in Windows-1252 encoding. Open with encoding='windows-1252' or convert to UTF-8 first.
Related tools
- CSV to JSON — convert CSV data to JSON
- CSV Quoting Rules — how CSV handles commas and quotes
- JSON Formatter — format and validate your JSON output
Related posts
- CSV Quoting and Escaping Rules (the Real Ones, Not the Folklore) — CSV looks trivial until your spreadsheet has a comma in a name field. Here's the…
- CSV Data Validation — Schema Validation, Type Checking, and Error Reporting — Validate CSV files before importing them into a database or processing pipeline.…
- Import CSV to Database — PostgreSQL, MySQL, SQLite, and Node.js — Import CSV files into PostgreSQL, MySQL, and SQLite using COPY commands, LOAD DA…
- JSON Formatter — Why Formatting JSON Matters and How It Works — A JSON formatter takes compact, hard-to-read JSON and adds whitespace and indent…
- YAML to JSON Converter — Convert YAML Configuration to JSON — YAML to JSON conversion is lossless for most data types. Here's how the conversi…
Related tool
Convert CSV files to JSON with proper quoting and escaping.
Written by Mian Ali Khalid. Part of the Data & Format pillar.