CSV to JSON Converter

Paste, Upload or Load a Sample to Convert CSV to JSON

Advanced

CSV

JSON

JSON to CSV 0 rows 0 columns 0 B

About the CSV to JSON Converter

This free CSV to JSON Converter turns CSV into JSON as soon as you paste it. You can also upload one or more files, import a file from a URL, or load a sample dataset to see how the settings work. Each row becomes a JSON object keyed by your column headers, and the conversion runs in your browser, so your data stays on your device.

Contents [hideshow]

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?

  1. 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.
  2. 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.
  3. If the output isn't what you expected, change the settings. The table below explains each one.
  4. 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
SeparatorAuto-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 headersEach 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 linesBlank lines are left out of the output.Turn it off only if blank lines stand for real records.
Auto-detect numbers and booleans42 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 linesDrops 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 prefixLines starting with it, # by default, are ignored.Clear it if real data can start with #.
Trim whitespaceRemoves spaces around keys and values.Turn it off when leading or trailing spaces are part of the value.
Convert keys to lowercaseName, NAME, and name all become name.Headers come from different exports, or the code reading the JSON expects lowercase keys.
Normalize JSONEvery 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 JSONWrites 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 objectsdf.to_json(orient='records')
Array of arrays (no header row)df.to_json(orient='values')
Keyed by IDdf.set_index('id').to_json(orient='index')
Column-orientedjson.dumps(df.to_dict(orient='list'))
JSON Linesdf.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:

JavaScript
// {"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:

Python
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:

Python
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:

Python
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:

JavaScript
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:

JavaScript
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:

Bash
# 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:

Bash
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:

PowerShell
$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.

Frequently Asked Questions

Paste the CSV into the left panel, upload a .csv file, or import one from a URL, and the JSON appears in the right panel straight away. With Use first row as headers switched on, each data row becomes an object keyed by the header names, so name,age followed by Ada,36 becomes [{"name": "Ada", "age": 36}]. Adjust the separator or type detection if needed, then select Copy or Download to save the result as a .json file. For URL imports, the link must point to the raw CSV file and the host must allow cross-origin (CORS) requests.

CSV is a flat, plain-text table: one record per line, fields separated by commas, and no data types, so 42 and "42" look identical. JSON stores structured data as objects and arrays with explicit strings, numbers, booleans, and null, and it can nest values inside one another. CSV is compact and opens in any spreadsheet, which suits exports and bulk data. JSON is the native format of web APIs and JavaScript, and suits configuration files and document databases. To go the other way, use the JSON to CSV Converter.

Yes, when Use first row as headers is on, which is the default. Each header becomes a key and every row below it becomes one object: id,name followed by 1,Ada converts to [{"id": 1, "name": "Ada"}]. Turn the option off and the header is treated as data, so every row becomes an array instead: [["id", "name"], [1, "Ada"]]. Duplicate headers are kept apart with a numeric suffix (id and id_1), spaces around keys and values are trimmed (untick Trim whitespace under Advanced to keep them), and Convert keys to lowercase turns Name into name.

Leave Separator on Auto-detect: it recognizes commas, tabs, semicolons, and pipes on its own. For data separated by colons, spaces, carets (^), or tildes (~), choose that character from the Separator dropdown, because those are not guessed. Files ending in .tsv, .psv, .ssv, and .txt can be uploaded directly alongside .csv. One catch with semicolon files from European locales: a decimal written as 9,99 stays the string "9,99", since only a dot is read as a decimal point.

They follow RFC 4180, the CSV specification: a field containing a comma, a double quote, or a line break is wrapped in double quotes, and any quote inside it is escaped by doubling it. So "Smith, John" becomes the single value Smith, John, and "She said ""hi""" becomes She said "hi", which JSON writes as "She said \"hi\"". A quoted field can also span several lines and still count as one cell. If a quote is never closed, everything after it is swallowed into one field, so check that quotes are balanced when rows go missing.

Yes, while Auto-detect numbers and booleans is ticked. Values such as 42, -0.5, and 1e3 become JSON numbers, true and false (or TRUE and FALSE) become booleans, and empty cells become null. Everything else stays a string, including dates like 2024-01-05, the word null, and integers too large to store exactly (above 9,007,199,254,740,991), which are kept as text so no digits are lost. Untick the option to keep every value as a string, with empty cells as "".

Because type detection read the value as a number, and JSON numbers cannot carry leading zeros. A ZIP code such as 02134 becomes 2134, and a product code like 007 becomes 7. Untick Auto-detect numbers and booleans and they are kept as the strings "02134" and "007". The same fix protects phone numbers, account numbers, and other codes that only look numeric. The setting applies to the whole file, so genuine number columns become strings as well; convert those back in your own code if needed.

Usually a parse setting dropped them on purpose. Comment prefix is set to # by default, so any line starting with # is skipped, including a data row such as #2,Bob; clear the field to keep those rows. Skip empty lines removes blank lines, and Skip first N lines discards that many lines from the top of the file. Both Comment prefix and Skip first N lines sit under Advanced, below the main settings. If several rows have merged into one long value instead, look for an unclosed double quote just above them.

Not with this converter. It produces a flat array with one object per row, and a header such as user.name stays a literal key, giving {"user.name": "Ada"}. Flat output maps cleanly onto tables, APIs, and database imports, which covers most CSV data. If you need {"user": {"name": "Ada"}}, convert here first and then split each key on the dot in a short script, or use a library such as Lodash, whose _.set(obj, 'user.name', value) builds the nested path for you.

Save the sheet as CSV first, then convert the CSV, because the converter does not read .xlsx files. In Excel, choose File > Save As and pick CSV UTF-8 (Comma delimited), which keeps accented letters and symbols intact; in Google Sheets, use File > Download > Comma-separated values. Only the active sheet is saved, so repeat for each sheet you need. In regions that use a comma as the decimal mark, Excel separates fields with semicolons, which Auto-detect handles. If an export starts with a sep=; line, set Skip first N lines to 1.

The file is almost certainly not encoded as UTF-8. The converter reads every file as UTF-8, so a CSV saved in an older encoding such as Windows-1252, which Excel's plain CSV (Comma delimited) option produces on many Windows systems, turns characters like é and £ into the replacement symbol �. Re-save the file as CSV UTF-8 in Excel, or as UTF-8 in your text editor, and upload it again. A UTF-8 byte order mark (BOM), which Excel adds to CSV UTF-8 files, is stripped automatically, so it never ends up inside the first key.

In Python, the standard library is enough: after import csv, json, the call json.dumps(list(csv.DictReader(open('data.csv', newline='', encoding='utf-8-sig'))), indent=2) returns an array of objects, although every value stays a string. With pandas, pd.read_csv('data.csv').to_json('data.json', orient='records', indent=2) writes the file and keeps numbers as numbers. In Node.js, install PapaParse, the parser this converter is built on, and run Papa.parse(fs.readFileSync('data.csv', 'utf8'), { header: true, dynamicTyping: true, skipEmptyLines: true }).data to get the same typed array of objects.

Each uploaded file can be up to 25 MB. Parsing runs in a background Web Worker, so the page stays responsive while a multi-megabyte file converts. To keep the browser fast, each panel displays only the first 100 KB of CSV or JSON and shows a notice when the view is cut short, but Copy and Download always deliver the complete JSON rather than the preview. A cut-short CSV view is read-only, so an edit can never drop the rows out of view. For files above 25 MB, split them into smaller parts, or parse them in code with a streaming option such as PapaParse's step callback.

Yes. Select several files in the upload dialog or drag them onto the CSV input, and each one is converted separately with the same settings. Switch between results with the file tabs above the JSON panel, use Download to save the file in view as name-to-json.json, or use Download All to get every result in a single ZIP archive. You can add more files later without losing the ones already converted, and any file over 25 MB or with an unsupported extension is skipped with a message.

Yes. The converter is free, requires no sign-up, and has no row or usage limits beyond the 25 MB cap per file. Conversion runs entirely in your browser, so pasted data and uploaded files are never sent to or stored on Syntax Toolbox servers. When you import from a URL, your browser fetches the file directly from its source instead of routing it through our servers. Your data is not saved between visits (only your settings are), so closing or refreshing the tab clears it.

We Value Your Opinion

Does this tool meet your expectations? Your feedback helps us improve

By submitting, you agree to our Terms of Use & Privacy Policy

Find Syntax Toolbox useful? Support us