How to Convert JSON to CSV: Nested Data and Excel Pitfalls

To convert JSON to CSV, turn each object into one row and each key into one column, using the keys from every record rather than only the first. Then decide what happens to nested data: flatten objects into columns like customer.name, keep arrays as JSON text in a single cell, or expand an array into one row per item. Quote any field that contains a comma, a double quote or a line break, and double the quotes inside it. Before opening the file in Excel, import ID columns as text so leading zeros and long numbers survive.

For a quick conversion in your browser, paste your data into the FindPicked JSON to CSV converter. It keeps nested values as JSON text and protects formula-like cells by default. The rest of this guide shows what each choice produces, using outputs we generated with the converter’s own code, Python, pandas and jq.

The short version

  1. Decide what one row means. One order? One order line? This decides how arrays are handled.
  2. Collect every key. A field that first appears in record 500 still needs a column.
  3. Pick a nested-data policy. Keep as JSON text, flatten objects, or expand arrays into rows.
  4. Let a CSV library do the quoting. Commas, quotes and line breaks inside values need escaping.
  5. Keep identifiers as strings. Quote IDs in the JSON, and import them as text in spreadsheets.
  6. Check the result. Count rows and columns, and open a few records you know.

The example data

Every CSV output below comes from this small file, orders.json. It has a nested object, an array of objects, a value with a comma and quotes, a null, a formula-like string and a key that appears only in the second record:

[
  {
    "id": "0012",
    "customer": {"name": "Ana Ruiz", "city": "Lima"},
    "items": [{"sku": "A-1", "qty": 2}, {"sku": "B-7", "qty": 1}],
    "total": 31.5,
    "note": "Ring twice, \"blue\" door"
  },
  {
    "id": "0013",
    "customer": {"name": "Lin", "city": null},
    "items": [{"sku": "C-3", "qty": 5}],
    "total": 12,
    "note": "=1+1",
    "coupon": "MARCH1"
  }
]

If you are not sure your input is valid JSON, run it through the JSON formatter first. A converter cannot fix a missing bracket for you.

Decide what a row is

This is the decision that matters most, and no tool can make it for you. If one row is one order, the two items in order 0012 must fit into a single row somehow. If one row is one order line, order 0012 becomes two rows, and its customer details repeat on both. Both are correct, but they answer different questions: per-order totals or per-product quantities.

There are three common policies:

Policy Rows in our example Good for Cost
Keep nested values as JSON text 2 Round trips, archiving, debugging Cells contain JSON that people must read
Flatten objects into dotted columns 2 Objects such as customer Arrays still need a decision
One row per array item 3 Lists such as items Parent fields repeat; totals can double-count

Option 1: keep nested values as JSON text

This is the FindPicked converter’s default. We ran the converter’s JavaScript, the same file the tool page loads, unchanged in Node 24 on the example. It produced this output, with CRLF line endings:

"id","customer","items","total","note","coupon"
"0012","{""name"":""Ana Ruiz"",""city"":""Lima""}","[{""sku"":""A-1"",""qty"":2},{""sku"":""B-7"",""qty"":1}]","31.5","Ring twice, ""blue"" door",""
"0013","{""name"":""Lin"",""city"":null}","[{""sku"":""C-3"",""qty"":5}]","12","'=1+1","MARCH1"

Notice four things. The coupon column exists even though the first record lacks it. The first record’s missing coupon became an empty cell. Every quote inside a value is doubled. And =1+1 gained a leading apostrophe, which is the converter’s formula protection (more on that below). The converter’s warnings flagged the missing field, the nested values and the formula prefix, for example “4 nested values stored as JSON text inside a cell”. If you choose the “Report an error instead” option, the same input stops with an error, which is useful when the destination only accepts flat records.

Option 2: flatten objects into dotted columns

Flattening turns {"customer": {"name": "Lin"}} into a column called customer.name. This Python script uses only the standard library. It flattens objects, keeps arrays as JSON text, and builds the column list from every record:

import csv
import json
import sys


def flatten(obj, prefix=""):
    row = {}
    for key, value in obj.items():
        name = prefix + key
        if isinstance(value, dict):
            row.update(flatten(value, name + "."))
        elif isinstance(value, list):
            row[name] = json.dumps(value, ensure_ascii=False)
        elif isinstance(value, bool):
            row[name] = "true" if value else "false"
        else:
            row[name] = value  # None becomes an empty cell
    return row


with open(sys.argv[1], encoding="utf-8") as f:
    rows = [flatten(record) for record in json.load(f)]
columns = list(dict.fromkeys(key for row in rows for key in row))

with open(sys.argv[2], "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=columns)
    writer.writeheader()
    writer.writerows(rows)

Running python3 flatten.py orders.json orders-flat.csv (Python 3.14) wrote:

id,customer.name,customer.city,items,total,note,coupon
0012,Ana Ruiz,Lima,"[{""sku"": ""A-1"", ""qty"": 2}, {""sku"": ""B-7"", ""qty"": 1}]",31.5,"Ring twice, ""blue"" door",
0013,Lin,,"[{""sku"": ""C-3"", ""qty"": 5}]",12,=1+1,MARCH1

Python’s csv module quotes only fields that need it. The Python documentation explains why the file is opened with newline="": without it, line breaks inside quoted fields are not handled correctly. Booleans get explicit handling because Python would otherwise write True and False. This script does not protect formulas, so =1+1 is written as is.

Option 3: one row per array item

When the array is the thing you want to analyze, expand it. pandas.json_normalize does this with record_path, and copies parent fields with meta:

import json

import pandas as pd

with open("orders.json", encoding="utf-8") as f:
    data = json.load(f)

items = pd.json_normalize(data, record_path="items",
                          meta=["id", ["customer", "name"]])
items.to_csv("order-items.csv", index=False)

With pandas 3.1.1, order-items.csv contained three rows, and the IDs kept their leading zeros because they were strings in the JSON:

sku,qty,id,customer.name
A-1,2,0012,Ana Ruiz
B-7,1,0012,Ana Ruiz
C-3,5,0013,Lin

The same expansion with jq 1.7.1, whose @csv filter quotes strings and doubles inner quotes:

jq -r '(["id","sku","qty"]), (.[] | .id as $id | .items[] | [$id, .sku, .qty]) | @csv' orders.json
"id","sku","qty"
"0012","A-1",2
"0012","B-7",1
"0013","C-3",5

One warning about this shape: an order-level value such as total repeats on every line of that order. Summing it per row would count order 0012 twice. Keep order-level and line-level values in separate files if both matter.

Quoting and escaping rules

CSV has no single binding standard, but RFC 4180 documents the common format. Its rules cover the cases that break naive converters:

Value Written as Rule
Ring twice, door "Ring twice, door" A field containing a comma is enclosed in double quotes
"blue" door """blue"" door" A double quote inside a field is escaped by doubling it
A note with a line break "Line one + newline + Line two" A field containing a line break is enclosed in quotes

RFC 4180 uses CRLF line endings and an optional header row. Both the FindPicked converter and Python’s csv module write CRLF by default. Never build CSV by joining strings with commas yourself; the first address with a comma in it will shift every column after it.

Empty values are where CSV loses information. A null, a missing key and an empty string all become an empty cell. In our example, the converter noted “1 missing fields and 0 null values exported as empty cells”. The null city sits inside the nested customer object, which stays JSON text in this mode. If the difference matters, add an explicit column before converting.

Large numbers and identifiers

JSON numbers are not always safe. RFC 8259 notes that many parsers use IEEE 754 double precision, so implementations are only guaranteed to agree exactly on integers between -(2^53)+1 and (2^53)-1. We parsed a record containing "id": 9007199254740993, which is 2^53 + 1, with four tools:

Tool Result
Node 24 JSON.parse 9007199254740992 (silently changed)
Python 3.14 json 9007199254740993
jq 1.7.1 9007199254740993
FindPicked converter Stops with an error asking you to quote the value

The fix is at the source: store IDs, account numbers and postal codes as JSON strings, such as "id": "9007199254740993". The converter then exports them exactly.

Opening the CSV in Excel without damage

A correct CSV file can still be changed when a spreadsheet opens it. Microsoft documents several automatic conversions:

  • Leading zeros disappear. According to Microsoft, Excel “automatically removes leading zeros” and converts large numbers to scientific notation, so 0012 becomes 12.
  • Long numbers lose digits. Excel has a maximum precision of 15 significant digits, and digits past the 15th are rounded down to zero. Microsoft says codes of 16 digits or more must use a text format.
  • Text can become dates. Researchers found in 2016 that Excel’s default settings turned gene symbols such as SEPT2 and MARCH1 into “2-Sep” and “1-Mar”. Our sample coupon code MARCH1 is that kind of value.
  • UTF-8 may display as garbled text. Microsoft notes that a UTF-8 CSV opens normally if it was saved with a byte order mark (BOM). In Python, encoding="utf-8-sig" writes one. Only add it for Excel, since some other tools treat the BOM as part of the first column name.

The safest route is to import instead of double-clicking. Microsoft’s guide to keeping leading zeros uses Data > From Text/CSV, then sets the column’s data type to Text in Power Query. Excel for Microsoft 365 and Excel 2024 also have automatic data conversion settings that can turn off the leading-zero, 15-digit, scientific notation and date conversions when opening CSV files. Microsoft notes that these settings do not directly affect Power Query imports.

Formula injection

A cell that starts with =, +, - or @ can be run as a formula. OWASP also lists tab, carriage return and line feed, plus full-width versions of those symbols. If your JSON contains text from users, someone could plant a formula that runs when a colleague opens the export.

The FindPicked converter prefixes such text with an apostrophe, which is why =1+1 became '=1+1 above. That changes the stored text, and OWASP warns the technique is not reliable in Excel after the file is saved and reopened. Treat it as one layer of defense: keep the protection on for untrusted data, and import the file as text.

Going the other way

If you need CSV to JSON instead, use the CSV to JSON converter, which handles quoted commas, escaped quotes and multiline fields, and keeps values as strings by default. The CSV to JSON walkthrough has a six-record test file you can check your result against. To check exports before converting, the CSV deduplicator finds repeated keys and the CSV comparison tool shows what changed between two snapshots.

How we tested

On November 17, 2026, we ran every command and script shown here on macOS: the FindPicked converter code in Node 24.16, Python 3.14.7, pandas 3.1.1 and jq 1.7.1. The CSV blocks above are the actual outputs. We did not test Excel itself. The spreadsheet behavior comes from Microsoft’s documentation and the 2016 study linked above, and can differ by version and settings.

Frequently Asked Questions

How do I convert nested JSON to CSV?

Choose a policy for each nested field. Flatten nested objects into dotted columns such as customer.name, keep arrays as JSON text inside one cell, or expand an array into one row per item and repeat the parent fields. CSV has no nesting, so every converter makes one of these choices, and you should make it deliberately.

Why does Excel remove the leading zeros from my CSV?

When Excel opens a CSV file directly, it converts number-like text into numbers, which drops leading zeros and keeps only 15 significant digits. Import the file with Data > From Text/CSV and set ID columns to Text, or turn off the automatic data conversion options in Excel for Microsoft 365 or Excel 2024.

Should every CSV field be quoted?

It is allowed but not required. RFC 4180 says fields containing commas, double quotes or line breaks should be enclosed in double quotes, with inner quotes doubled. Quoting every field is also valid, but quotes do not stop a spreadsheet from changing a value’s type.

What happens to null values when converting JSON to CSV?

A null, a missing key and an empty string all become an empty cell, so CSV cannot tell them apart. If the difference matters, add an explicit status column before converting or keep that data in JSON.