How to Convert JSON to CSV: Flattening Nested Objects and Arrays Without Losing Data
Turn JSON into a clean CSV file. Learn how to flatten nested objects, handle arrays, deal with missing keys, and avoid number and encoding problems.
You pull some data from an API, or export it from a database tool, and what you get is a .json file. Then somebody asks for it “in a spreadsheet.” For flat data this is a one-click job. For anything with a bit of structure, it turns into a long afternoon.
The reason is simple. JSON is a tree: objects inside objects, lists inside those. CSV is a grid: rows and columns, nothing else. Converting one to the other means making decisions about how the tree should be squashed flat, and a converter that makes those decisions without telling you can quietly lose data.
This guide covers what those decisions are. I’ll go through how to work out what shape your JSON has, how to flatten nested objects, three ways to handle arrays, the things CSV can’t remember about your data, and a few ways to do the conversion itself (browser, Python, and jq). Then there’s a short check to run on the result.
Why JSON doesn’t fit neatly into a grid
Here’s a single order, the kind of thing a shop’s API might return:
{
"order_id": "1001",
"customer": { "name": "Ana Rao", "city": "Pune" },
"items": [
{ "sku": "PEN-01", "qty": 2 },
{ "sku": "BK-17", "qty": 1 }
],
"total": 49.5
}
Four fields at the top level, but they aren’t equal. order_id and total are simple values. customer is an object with its own fields. items is a list with two entries, each of which is also an object.
A CSV row has one cell per column and each cell holds one piece of text. So customer has to be split into separate columns, and items has to become something, though nobody agrees what. That second one is where most conversions go wrong.
First, work out what shape your JSON has
Before you convert anything, open the file and look at the first few lines. Nearly every JSON file you’ll meet is one of four shapes, and each one needs a slightly different approach.
An array of objects. The file starts with [ and each entry is a record. This is the easy case, and what most converters expect. Each object becomes a row.
A wrapper object with the records inside. The file starts with { and the actual list sits under a key like data, results, items or records, often next to things like page numbers and totals. Most APIs return this. You need to point the converter at that inner list, or strip the wrapper first. If a tool gives you a single row full of oddly named columns, this is usually why.
An object keyed by ID. Instead of a list, you get something like {"1001": {...}, "1002": {...}}. The keys are meaningful, but they aren’t inside the records. To keep them, they have to become a column of their own, say id, before or during the conversion.
JSON Lines. One complete JSON object per line, no surrounding brackets and no commas between them. Log exports and some database dumps look like this. It’s technically not a single valid JSON document, so many tools reject it. Wrapping the lines in [ ] with commas between them, or using a tool that reads it directly, fixes that.
Two minutes spent identifying the shape saves a lot of confusion later. If you can’t tell, paste the first 20 lines into a viewer and look at the brackets.
Nested objects: dot notation is the standard answer
For a nested object, the usual approach is to join the parent key and child key with a dot. The customer object becomes two columns, customer.name and customer.city. Go three levels deep and you get customer.address.postcode. The picture above shows exactly this.
It’s a convention, not a rule. Some tools use underscores (customer_name) or slashes. The dot is the most common, and it’s what Python’s json_normalize uses by default, so it’s safe to stick with unless the system receiving your CSV expects something else.
One thing to watch: if your data already has keys containing dots, like "user.id", you can end up with ambiguous column names. It’s rare, but if you hit it, choose a different separator.
Arrays: three ways to handle a list
Arrays are the hard part, because a CSV cell can’t hold a list. There are three workable strategies, and the right one depends on what you plan to do with the file.
Join into one cell. The array ["pen", "book"] becomes the text pen|book. You keep one row per record, which is good when you want a tidy overview. The downside is that the cell is now a string you have to split again if you want to count or filter items. Choose a separator that can’t appear in the data; the pipe is a good one.
One row per item. The order appears twice, once for each item, with the order fields repeated. This is the format spreadsheets and databases like best. It’s easy to filter by item, sum quantities, or pivot. The catch is that totals at the order level now appear twice, so summing the total column would double-count. That’s the classic mistake with this approach, so label it clearly or keep the order-level fields in a separate file.
Numbered columns. item_1, item_2, and so on. This only makes sense when arrays are short and roughly the same length, like a record that always has up to three phone numbers. With arrays of varying length you end up with a wide, sparse table where half the columns are empty, and one long record can add dozens of new columns.
My own default is one row per item whenever the array contains real records (like order lines), and joining into one cell when it’s a simple list of tags or labels. Numbered columns are the one I reach for least.
One more trap with the one-row-per-item approach: records whose array is empty. An order with "items": [] has nothing to expand into, so many tools, json_normalize with record_path included, drop that order from the output entirely. Nobody gets an error. The row count just comes out lower than you expected, and the missing records are usually the ones that would have been worth a second look. If empty arrays can occur in your data, keep a separate count of records in the source, or convert with a join-into-one-cell strategy first and compare the totals.
For arrays of objects, like the items list above, you can combine approaches: one row per item, with the item’s own fields flattened (items.sku, items.qty) alongside the parent fields.
When objects have different keys
Real JSON is rarely uniform. One record has a discount field, another doesn’t. A third has a notes field nobody else uses. This is called a ragged or sparse structure, and CSV handles it only if the converter does the right thing.
The right thing is to collect every key that appears anywhere in the file, use that full set as the header, and leave cells empty where an object doesn’t have that key. The wrong thing is to look only at the first object and use its keys as the header. Do that, and discount and notes silently vanish, and nothing warns you.
You can test any converter in 30 seconds. Make a tiny file where the second record has an extra key, convert it, and see whether the column appears. If it doesn’t, don’t trust that tool with real data.
What CSV can’t remember
Once your JSON is a CSV, a few things are lost, and it helps to know which ones before they cause trouble.
The difference between null and empty. JSON distinguishes null, "" (an empty string) and a missing key. CSV shows all three as an empty cell. If that distinction matters to whoever uses the data, you’ll need a convention, like writing NULL for nulls, and you’ll have to agree on it with them.
Types. Numbers, booleans and strings all become text. true becomes the word true. A spreadsheet will usually guess types when it opens the file, and sometimes it guesses wrong.
Large and padded numbers. JavaScript-based parsers read JSON numbers as floating point, which can only hold integers exactly up to 9,007,199,254,740,991. A 19-digit ID stored as a number can come out with its last few digits changed. If your IDs are long, they should be strings in the JSON ("id": "1234567890123456789"), and you should check any ID column against the original. The same goes for values like postal codes with leading zeros, which only survive if they were strings to begin with.
Dates. JSON has no date type. Dates are strings, usually ISO 8601 like 2026-11-09T14:30:00Z. They’ll come through as text unchanged, which is good, but Excel may then reinterpret them when you open the file.
Formulas that you didn’t mean to write. If any text value starts with =, +, - or @, Excel may treat it as a formula when someone opens the CSV. It’s a real security issue called CSV injection when the data comes from users you don’t control. If your JSON includes free-text from outside sources, prefix those values with a single quote or tab before exporting.
Encoding. JSON is almost always UTF-8, so keep the CSV in UTF-8 too. If the person opening it uses Excel on Windows, saving with a byte order mark helps it detect the encoding correctly. Our guide on exporting Excel to CSV without corrupting data covers the encoding side in more detail.
Convert JSON to CSV in your browser
For a one-off conversion, a browser tool is the quickest route, and it matters that the work stays on your device. API responses often contain customer details, order data or internal IDs, and uploading them to a random website isn’t something I’d do. Our post on why you shouldn’t upload sensitive CSVs to cloud converters explains the risks.
With the JSON to CSV converter:
- Open the page and paste your JSON or choose the file.
- Check that the preview shows the columns you expect, including dotted names for nested fields.
- Look for the problems above: a missing column, a column full of
[object Object], or a single row where you expected many. - Download the CSV.
- Open the result in the CSV viewer to check it before sending it to anyone.
The preview step is where problems show up. If something looks off, it’s almost always one of the shape issues mentioned earlier.
Converting with Python
If you convert JSON regularly, pandas has a function built for this job, json_normalize:
import json
import pandas as pd
with open("orders.json", encoding="utf-8") as f:
data = json.load(f)
df = pd.json_normalize(
data,
record_path="items",
meta=["order_id", "total", ["customer", "name"], ["customer", "city"]],
sep=".",
)
df.to_csv("orders.csv", index=False, encoding="utf-8-sig")
record_path="items" creates one row per item, and meta lists the parent fields to repeat on each row. Nested meta fields are given as a list of keys. If you drop record_path and meta, you get one row per top-level object with nested objects flattened using the separator you choose. The utf-8-sig encoding writes a byte order mark so Excel opens the file correctly; drop it if the file is going to code rather than a person.
For long numeric IDs, load with json.load as above, and make sure the source stores them as strings. Once the data has been parsed as numbers, the precision is already gone.
Converting with jq
On a terminal, jq can turn a flat array of objects into CSV in one line:
jq -r '(map(keys) | add | unique) as $cols
| $cols, (.[] | [.[$cols[]]])
| @csv' data.json
This collects every key across all records for the header, so missing keys are handled properly. It only works for flat data, though. Nested objects and arrays would need to be flattened first, and jq gets complicated quickly at that point. For anything with real nesting, I’d use Python or the browser tool instead. Note also that unique sorts the columns alphabetically, so the column order may not match the original.
Check the result before you use it
A short routine catches most problems:
- Count the rows. If you chose one row per record, the CSV should have as many data rows as the JSON has records. With one row per item, it should match the total number of array entries.
- Look for empty columns. A column that’s blank all the way down usually means a key was misspelled or nested deeper than expected.
- Spot-check a few values against the original, especially long IDs, decimals and any text with commas or quotes.
- Search for
[object Object]and forundefined. Either one means a value wasn’t flattened properly. - Open it where it will be used. If the file is going into Excel, open it in Excel. If it’s going into a database import, test the import with ten rows first.
If the file contains line breaks or commas inside text fields, check that they’re properly quoted. Our guide on fixing comma and newline errors in CSV fields shows what correct quoting looks like.
The short version
JSON is a tree and CSV is a grid, so every conversion involves decisions about nesting, arrays and missing keys. Work out the shape of your file, flatten nested objects with dots, pick an array strategy on purpose, and check the output against the source. Do those four things and the conversion stops being the part that goes wrong.
Frequently asked questions
Why do some cells show [object Object] after converting JSON to CSV?
That text appears when a converter meets a nested object and doesn't know how to flatten it, so it prints the object's default string form instead of its contents. The fix is to flatten nested objects into separate columns using dot notation, such as customer.name and customer.city, before or during the conversion.
How do I convert a JSON array inside each record into CSV?
You have three options. You can join the array items into one cell with a separator, create one row per array item and repeat the parent fields, or create numbered columns such as item_1 and item_2. Joining keeps one row per record, one row per item is easiest to filter and sum, and numbered columns work only when arrays are short and similar in length.
What happens when JSON objects have different keys?
A good converter collects every key that appears in any object and uses the full set as the CSV header. Objects that lack a key get an empty cell in that column. A weaker converter takes the columns from the first object only, which silently drops fields that appear later in the file.
Can a CSV file keep the data types from my JSON?
No. CSV stores everything as text, so numbers, booleans, nulls and dates all become plain strings. A null and an empty string both end up as an empty cell, and very large numeric IDs should be stored as strings in the JSON to avoid precision loss when the file is parsed.
Is it safe to convert JSON that contains private data online?
Only if the conversion happens on your own device. Many online converters upload your file to a server. A client-side tool like RealCSVTools processes the JSON inside your browser, so API responses with customer or account data are never sent anywhere.