What Happens When CSV Becomes JSON
A CSV file is a table saved as plain text. The first line usually holds the column names, and each line after it is one record. Converting it to JSON keeps the records but writes them differently: the column names become keys, and each row becomes an object that pairs those keys with its values. This CSV:
id,name,city
1,Ada,Pune
2,Ravi,Boston becomes this JSON:
[
{ "id": 1, "name": "Ada", "city": "Pune" },
{ "id": 2, "name": "Ravi", "city": "Boston" }
] Two things change on the way. Values get types, so 1 is now a number and Pune a string, where in the CSV both were just text. And every value now carries its own name, so a program reading the file no longer needs to know that the third column is the city. That makes JSON easier for code to work with, and it is what web APIs typically send and receive.
How to Use the Syntax Toolbox CSV to JSON Converter?
- Add your CSV. Paste or type it into the CSV panel, drag files onto it, select Upload to choose .csv, .tsv, .psv, .ssv, or .txt files, or select URL to import a file from a link. Sample loads one of three small datasets if you want to try the settings first.
- Read the result in the JSON panel. It updates as you type, and the bar below it shows how many rows and columns were found and how big the JSON is.
- If the output isn't what you expected, change the settings. The table below explains each one.
- Select Copy, or Download to save a .json file. With several files, switch between them using the tabs above the JSON panel, and select Download All to get them in one ZIP.
To go back the other way, the JSON to CSV button under the JSON panel opens the result in the JSON to CSV Converter.
What Each Setting Does
The defaults suit most files. The last six settings sit under Advanced.
| Setting | What It Does | When to Change It |
|---|---|---|
| Separator | Auto-detect reads the first 10 rows and picks a comma, tab, semicolon, or pipe. | Choose one yourself for colon, space, caret, or tilde files, or when Auto-detect picks the wrong character. |
| Use first row as headers | Each row becomes an object keyed by the header names. | Turn it off when the file has no header row. Each row then becomes an array of values. |
| Skip empty lines | Blank lines are left out of the output. | Turn it off only if blank lines stand for real records. |
| Auto-detect numbers and booleans | 42 becomes a number, true a boolean, and an empty cell null. | Turn it off to keep ZIP codes, phone numbers, and IDs exactly as written. |
| Skip first N lines | Drops that many lines from the top before reading the header. | Reports that start with a title or date line, and Excel exports that start with sep=;. |
| Comment prefix | Lines starting with it, # by default, are ignored. | Clear it if real data can start with #. |
| Trim whitespace | Removes spaces around keys and values. | Turn it off when leading or trailing spaces are part of the value. |
| Convert keys to lowercase | Name, NAME, and name all become name. | Headers come from different exports, or the code reading the JSON expects lowercase keys. |
| Normalize JSON | Every object gets every key, with gaps filled with null. | Rows have different lengths and the code reading the JSON expects the same keys on every object. |
| Minify JSON | Writes the whole array on one line with no spaces. | The JSON goes into a request, a config value, or storage, where nobody reads it by eye. |
Choosing a JSON Output Shape
There is more than one way to write a table as JSON, and libraries don't all pick the same one by default. Here is the same two-row CSV from above in each of the common layouts.
Array of Objects
[
{ "id": 1, "name": "Ada", "city": "Pune" },
{ "id": 2, "name": "Ravi", "city": "Boston" }
] One object per row, and the layout this converter produces. It is easy to read and easy to loop over. The cost is size, because every key is repeated on every row.
Array of Arrays
[
["id", "name", "city"],
[1, "Ada", "Pune"],
[2, "Ravi", "Boston"]
] Turn off Use first row as headers to get this layout. Each row is a plain list, so the file is smaller and the column order is kept, but the code reading it has to know what each position means. The Google Sheets API reads and writes cell ranges in this form.
Keyed by ID
{
"1": { "name": "Ada", "city": "Pune" },
"2": { "name": "Ravi", "city": "Boston" }
} Useful when code looks records up by ID instead of looping through them. JSON keys are always strings, so the number 1 becomes "1", and the IDs must be unique, or a later row replaces an earlier one. In JavaScript, keys that look like whole numbers are also sorted in ascending order when the object is read, so a file keyed 10, 2 comes back as 2, 10.
Column-Oriented JSON
{
"id": [1, 2],
"name": ["Ada", "Ravi"],
"city": ["Pune", "Boston"]
} Each column becomes one array. Charting libraries and data analysis code often want data this way, because a whole column can be passed in at once. Row 2 is whatever sits at position 1 in every array.
JSON Lines (NDJSON)
{"id": 1, "name": "Ada", "city": "Pune"}
{"id": 2, "name": "Ravi", "city": "Boston"} One object per line, with no surrounding brackets and no commas between records. The file as a whole isn't valid JSON, so parsing it in one go fails, but each line parses on its own. Programs can therefore read it one record at a time and add records to the end without rewriting the file. BigQuery, Elasticsearch's bulk API, and many logging tools take this format, also called newline-delimited JSON or NDJSON.
Matching Each Shape to pandas orient
In Python, pandas writes all of these from the same DataFrame. The orient argument picks the layout:
| Shape | pandas Call |
|---|---|
| Array of objects | df.to_json(orient='records') |
| Array of arrays (no header row) | df.to_json(orient='values') |
| Keyed by ID | df.set_index('id').to_json(orient='index') |
| Column-oriented | json.dumps(df.to_dict(orient='list')) |
| JSON Lines | df.to_json(orient='records', lines=True) |
| Each column keyed by row number (default) | df.to_json() |
Note the default: call df.to_json() with no arguments and
each column comes out as an object keyed by row number, as in
{"id": {"0": 1, "1": 2}}, which looks nothing like the CSV. Pass
orient='records' for one object per row.
Empty Cells: null, Empty String, or No Key
A blank cell in a CSV can mean nobody filled it in, the value is unknown, or the field doesn't apply. JSON has three ways to write it, and the converter's settings decide which one you get:
- null: With Auto-detect numbers and booleans on, an empty cell
becomes null, so the row 3,Mei, gives
"city": null. - Empty string: With that option off, the same cell stays
"". Python's csv.DictReader and PowerShell's Import-Csv give you this too. - No key: A row with fewer values than the header, such as 3,Mei with no comma at the end, leaves the missing keys out completely. Normalize JSON adds them back as null.
The difference matters most when the JSON updates existing records. Under JSON Merge Patch (RFC 7396), which many REST APIs use for updates, null deletes a field and a missing key leaves it as it was. A schema that requires a string will reject null but accept "". If you don't know what the receiving code expects, keep type detection on and turn on Normalize JSON. Every object then has the same keys, and every blank shows up as null, which is easy to search for.
Turning Flat CSV into Nested JSON
CSV has no way to put one value inside another, so nested data arrives flattened in one of two ways: the headers spell out a path, such as user.name, or one record is spread across several rows. The converter keeps the output flat in both cases. When you need the nesting back, a few lines of code will do it.
From Dot Notation Headers
A header such as user.name comes through as a key with a dot in it. To rebuild the objects, split each key on the dots and create an object at each step:
// {"user.name": "Ada"} -> {"user": {"name": "Ada"}}
function unflatten(row) {
const out = {};
for (const [path, value] of Object.entries(row)) {
const keys = path.split('.');
let node = out;
keys.slice(0, -1).forEach((key) => {
node[key] ??= {};
node = node[key];
});
node[keys.at(-1)] = value;
}
return out;
}
const nested = rows.map(unflatten);
Run on the converter's output, this turns {"id": 1, "user.name": "Ada", "user.email": "ada@example.com"}
into {"id": 1, "user": {"name": "Ada", "email": "ada@example.com"}}. It treats every dot
as a level, so rename any header where the dot belongs to the name itself, such as a column called
example.com.
Grouping Rows into Arrays
Order exports often repeat the order details on every line, once for each item:
order_id,customer,sku,qty
1001,Ada,A1,2
1001,Ada,B2,1
1002,Ravi,A1,5 To get one object per order with its items in an array, group the rows by order ID as you read them:
import csv
import json
orders = {}
with open('orders.csv', newline='', encoding='utf-8-sig') as f:
for row in csv.DictReader(f):
order = orders.setdefault(row['order_id'], {
'order_id': int(row['order_id']),
'customer': row['customer'],
'items': [],
})
order['items'].append({'sku': row['sku'], 'qty': int(row['qty'])})
with open('orders.json', 'w', encoding='utf-8') as f:
json.dump(list(orders.values()), f, indent=2, ensure_ascii=False)
# [{"order_id": 1001, "customer": "Ada",
# "items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}]},
# {"order_id": 1002, "customer": "Ravi",
# "items": [{"sku": "A1", "qty": 5}]}] setdefault creates the order the first time its ID appears and returns the same order
every time after that, so the items collect under it. The int() calls are there because
csv.DictReader reads every value as text. In JavaScript, the same approach works with a Map keyed by
order ID.
How to Convert CSV to JSON in Code
For a one-off file, the converter is quicker. For a script or a job that runs on a schedule, every major language has a CSV parser. The FAQs below include one-line versions; the examples here deal with the problems those one-liners skip. Each one reads this users.csv, saved from Excel as CSV UTF-8:
id,name,city,zip
1,Ada,Pune,411001
2,Ravi,Zürich,02134
3,Mei,,94107 CSV to JSON in Python
The standard library is enough:
import csv
import json
with open('users.csv', newline='', encoding='utf-8-sig') as f:
rows = list(csv.DictReader(f))
with open('users.json', 'w', encoding='utf-8') as f:
json.dump(rows, f, indent=2, ensure_ascii=False)
Three arguments in there prevent problems later. encoding='utf-8-sig' removes the byte
order mark that Excel puts at the start of CSV UTF-8 files. With plain utf-8 it stays attached to the
first header, and row['id'] fails with a KeyError because the key is really
'\ufeffid'. newline='' lets the csv module handle line breaks inside quoted
fields correctly. ensure_ascii=False writes Zürich as Zürich instead of
Z\u00fcrich, which is valid JSON but hard to read. Every value comes out as a string, so
convert numbers yourself.
pandas works out the types for you:
import pandas as pd
df = pd.read_csv('users.csv', dtype={'zip': str})
df.to_json('users.json', orient='records', indent=2, force_ascii=False)
That guessing is mostly helpful, but pandas read the ZIP code 02134 as the number 2134, so the
dtype argument keeps that column as text. Empty cells come out as null.
force_ascii=False does the same job as ensure_ascii above, and
orient='records' avoids the column-keyed default.
CSV to JSON in JavaScript and Node.js
PapaParse, the parser this converter is built on, works the same way in the browser and in Node.js:
import fs from 'node:fs';
import Papa from 'papaparse';
const { data, errors } = Papa.parse(fs.readFileSync('users.csv', 'utf8'), {
header: true,
skipEmptyLines: true,
// Type every column except zip, so 02134 keeps its leading zero
dynamicTyping: (field) => field !== 'zip',
});
if (errors.length) console.warn(errors);
fs.writeFileSync('users.json', JSON.stringify(data, null, 2)); dynamicTyping takes a function as well as true or false, so you can type every column
except the ones that only look numeric. PapaParse also removes the byte order mark on its own. It
doesn't throw on a malformed row; it lists the problem in errors and carries on, so check
that array before you trust the output.
For a file too big to read into memory, pass a stream instead and handle one row at a time. Writing JSON Lines means nothing has to be held until the end:
import fs from 'node:fs';
import Papa from 'papaparse';
const out = fs.createWriteStream('users.jsonl');
Papa.parse(fs.createReadStream('users.csv'), {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
step: (result) => out.write(JSON.stringify(result.data) + '\n'),
complete: () => out.end(),
}); CSV to JSON on the Command Line
DuckDB, a database engine that runs as a single program with no server, can do the whole conversion in one command:
# Array of objects
duckdb -c "COPY (SELECT * FROM 'users.csv') TO 'users.json' (FORMAT json, ARRAY true)"
# JSON Lines: leave out ARRAY true
duckdb -c "COPY (SELECT * FROM 'users.csv') TO 'users.jsonl' (FORMAT json)" It detects the separator and the column types, and in our test it kept the whole zip column as text, leading zero included. It is built for large files, so it is a good choice when a CSV is too big for a browser tab. csvkit's csvjson command is another option, with keyed output and JSON Lines built in:
csvjson users.csv > users.json # array of objects
csvjson -I users.csv > users.json # keep every value as text
csvjson -k id users.csv > users.json # keyed by the id column
csvjson --stream users.csv > users.jsonl # JSON Lines
With type detection on, csvkit 2.2 wrote 1 as 1.0 and 02134 as 2134.0, so -I is often
the better choice. jq is sometimes suggested for this job too, but it has no CSV parser, and splitting
lines on commas breaks on quoted values. Convert with one of the tools above and pipe the JSON into jq
if you need to reshape it.
CSV to JSON in PowerShell
PowerShell has both halves built in:
$rows = @(Import-Csv users.csv)
ConvertTo-Json -InputObject $rows | Set-Content users.json -Encoding utf8
Import-Csv reads every value as a string and empty cells as "", so 1 comes out as "1". Passing the rows
with -InputObject keeps a one-row file as an array; piped into ConvertTo-Json, a single
row comes out as a bare object. ConvertTo-Json also stops at two levels of nesting by default, so add
-Depth with a higher number if you build nested objects like the grouped orders above.
Windows PowerShell 5.1 has two more quirks: it writes <, >, &, and ' as escape codes such as
\u003c, and -Encoding utf8 adds a byte order mark to the file. PowerShell 7
does neither.
Converting Large CSV Files
JSON is bigger than the CSV it comes from, because the keys are repeated on every row. The Products sample in the converter is 438 bytes as CSV, 1,351 bytes as formatted JSON, and 990 bytes minified. That is about three times the size formatted, and a bit over twice minified. Long headers and short values make the gap wider.
The converter takes files up to 25 MB each and parses them in a background worker, so the page stays responsive while it works. For bigger files, or when the JSON is headed for a database or a data pipeline, these help:
- Write JSON Lines instead of one array: The reader can process one line at a time instead of parsing the whole file before it can start.
- Stream the input: The PapaParse stream example and DuckDB both work through the file in pieces, so memory use stays low even for very long files.
- Split the file for the browser: If it has to go through an online tool, cut it into parts at line breaks and copy the header row to the top of each part. Don't cut through a quoted value that spans several lines.
Common CSV to JSON Mistakes
- Splitting lines on commas yourself:
line.split(',')breaks on a quoted value such as "Smith, John" and on fields that contain line breaks. A real CSV parser handles both. - Opening and re-saving the CSV in Excel first: Excel drops leading zeros, keeps only 15 significant digits of long numbers, and can rewrite dates in your regional format. Saving writes those changes back into the file before it ever reaches the converter.
- Placeholders in number columns: Type detection works cell by cell, so a price column holding 19.99 in most rows and N/A in one gives numbers plus one string, and code expecting numbers fails on that row. Clear placeholders such as N/A, -, or TBD so the cells are empty, and they come out as null.
- Expecting trailing zeros to survive: 89.50 becomes 89.5 once it is a JSON number, and a version number such as 1.10 becomes 1.1. That is fine for calculations, but turn off type detection when the exact text matters.
- Keying by a column that has duplicates: When you build an object keyed by ID, a repeated ID silently replaces the earlier record. Count the rows before and after.