Home › Blog

How to convert JSON to CSV

CSV is the simplest table format there is, which is both its strength and its problem. Below are three ways to turn a JSON array into CSV, and the cases where an .xlsx file is the safer choice.

CSV or Excel?

A CSV file is plain text: one line per row, values separated by commas, and quotes around values that contain a comma or a quote. It has no data types, no formatting and only one table. That makes it easy for scripts and databases to read, but it changes how Excel sees your data:

  • Excel guesses the type of each value when it opens a CSV. A postcode like 01234 loses its leading zero.
  • Long numeric IDs are shown in scientific notation, and Excel keeps only 15 significant digits.
  • In regions that use a comma as the decimal separator, Excel expects semicolons and may put everything in one column.

An .xlsx file stores types, so a string stays a string and a number stays a number. If a person will open the result in Excel, the JSON to Excel converter is usually the better target. If a program will read it, CSV is fine.

1. Convert to .xlsx, then save as CSV

  1. Paste or upload the JSON in the converter and download the .xlsx file.
  2. Open it in Excel and choose File › Save As.
  3. Pick CSV UTF-8 (Comma delimited) (*.csv) as the type, so non-English characters survive.

LibreOffice Calc does the same with File › Save As › Text CSV, where you can also choose the separator. Nested objects are already flattened into dotted columns by the converter, so the CSV gets them too.

2. JavaScript with SheetJS

SheetJS can build a sheet from JSON and print it as CSV, with the quoting handled for you. Install it from the SheetJS CDN, which is where current versions are published:

npm i https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
import * as XLSX from 'xlsx';

const rows = [
  { name: 'Ada, Countess', note: 'said "hi"' },
  { name: 'Bob' },
];
const csv = XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet(rows));

The result, with the comma and the quotes escaped and the missing value left empty:

name,note
"Ada, Countess","said ""hi"""
Bob,

json_to_sheet leaves nested objects and arrays out of the cells, so flatten them first. The JSON to Excel in JavaScript guide has a small flatten function.

3. The command line with jq

For a flat array of objects, jq can write CSV in one line. It takes the keys of the first object as the header and prints each record in that order:

jq -r '(.[0] | keys_unsorted) as $k | $k, (.[] | [.[$k[]]]) | @csv' people.json

For a file with two people this prints:

"name","city","age"
"Ada","London",36
"Grace, B.","New York",85

Keys that appear only in later records are dropped by this command, and nested values make @csv fail. For uneven or nested data, one of the two methods above is less work.