Converting JSON to CSV in the Terminal
Turn a JSON array of objects into CSV from the shell, without Python, using fx and JavaScript expressions.
Convert a JSON Array to CSV with a Header Row
Take the header from the first object's keys and rows from each object's values, join with commas, and print one line per row with list. Assumes identical keys and no commas or quotes in values:
fx users.json '[keys(x[0]), ...x.map(values)]' '@.join(",")' listInput:
[
{"id": 1, "name": "Alice", "email": "alice@example.com", "age": 31},
{"id": 2, "name": "Bob", "email": "bob@example.com", "age": 27},
{"id": 3, "name": "Carol", "email": "carol@example.com", "age": 45}
]Output:
id,name,email,age
1,Alice,alice@example.com,31
2,Bob,bob@example.com,27
3,Carol,carol@example.com,45Select and Reorder CSV Columns
Put the column names in an array. The same list sets both the header and the order of the values:
fx users.json 'x => {
const cols = ["email", "name", "age"];
return [cols, ...x.map(u => cols.map(c => u[c]))];
}' '@.join(",")' listOutput:
email,name,age
alice@example.com,Alice,31
bob@example.com,Bob,27
carol@example.com,Carol,45Escape Commas, Quotes, and Newlines in CSV
Values containing ,, ", or a line break must be wrapped in double quotes, with inner quotes doubled (RFC 4180). This csv helper does that and turns null into an empty cell:
fx products.json 'x => {
const csv = v => {
const s = v == null ? "" : String(v);
return /[",\n\r]/.test(s) ? `"${s.replaceAll(`"`, `""`)}"` : s;
};
const cols = Object.keys(x[0]);
return [cols, ...x.map(r => cols.map(c => r[c]))].map(row => row.map(csv).join(","));
}' listInput:
[
{"sku": "A-100", "name": "Desk, oak", "note": "Ships in 2 days"},
{"sku": "B-200", "name": "27\" monitor", "note": "Line one\nLine two"},
{"sku": "C-300", "name": "Chair", "note": null}
]Output:
sku,name,note
A-100,"Desk, oak",Ships in 2 days
B-200,"27"" monitor","Line one
Line two"
C-300,Chair,Flatten Nested JSON Fields into CSV Columns
Pick nested values by path, such as c.address.city, and give each one its own column name:
fx customers.json '[["id", "name", "city", "country"], ...x.map(c => [c.id, c.name, c.address.city, c.address.country])]' '@.join(",")' listInput:
[
{"id": 1, "name": "Alice", "address": {"city": "Berlin", "country": "DE"}, "tags": ["vip", "newsletter"]},
{"id": 2, "name": "Bob", "address": {"city": "Lyon", "country": "FR"}, "tags": []},
{"id": 3, "name": "Carol", "address": {"city": "Austin", "country": "US"}, "tags": ["beta"]}
]Output:
id,name,city,country
1,Alice,Berlin,DE
2,Bob,Lyon,FR
3,Carol,Austin,USJoin Array Values in a CSV Cell
CSV has no array type, so join the array into one cell. Use a separator other than the comma, such as ;:
fx customers.json '[["id", "name", "tags"], ...x.map(c => [c.id, c.name, c.tags.join(";")])]' '@.join(",")' listOutput:
id,name,tags
1,Alice,vip;newsletter
2,Bob,
3,Carol,betaConvert JSON to TSV
For tab-separated values, join each row with "\t" instead of ",":
fx users.json '[keys(x[0]), ...x.map(values)]' '@.join("\t")' listOutput:
id name email age
1 Alice alice@example.com 31
2 Bob bob@example.com 27
3 Carol carol@example.com 45Convert JSON Lines (NDJSON) to CSV
fx reads newline-delimited JSON one value at a time, so a single expression turns each line into a CSV row:
cat orders.ndjson | fx '[x.order, x.customer, x.total].join(",")'Input:
{"order": "A1", "customer": "alice", "total": 42.5}
{"order": "A2", "customer": "bob", "total": 13, "coupon": "SPRING"}
{"order": "A3", "customer": "carol", "total": 99.9}Output:
A1,alice,42.5
A2,bob,13
A3,carol,99.9To add a header, slurp all lines into one array with -s. Building the header from the union of all keys gives fields that appear in only some records, like coupon, their own column:
cat orders.ndjson | fx -s 'x => {
const cols = uniq(x.flatMap(keys));
return [cols, ...x.map(r => cols.map(c => r[c] ?? ""))];
}' '@.join(",")' listOutput:
order,customer,total,coupon
A1,alice,42.5,
A2,bob,13,SPRING
A3,carol,99.9,Save JSON as a CSV File
Redirect with > (not save, which overwrites the input JSON). Excel, LibreOffice Calc, Numbers, and Google Sheets can open the result:
fx users.json '[keys(x[0]), ...x.map(values)]' '@.join(",")' list > users.csvReusable toCSV Function in .fxrc.js
Define the helper once in .fxrc.js (current, home, or XDG config directory):
function csvCell(v) {
if (v == null) return ''
if (Array.isArray(v)) v = v.join(';')
else if (typeof v === 'object') v = JSON.stringify(v)
const s = String(v)
return /[",\n\r]/.test(s) ? '"' + s.replaceAll('"', '""') + '"' : s
}
function toCSV(rows) {
const cols = Object.keys(rows[0])
return [cols, ...rows.map(r => cols.map(c => r[c]))]
.map(row => row.map(csvCell).join(','))
.join('\n')
}toCSV returns a single string, and fx prints strings without JSON quotes. fx products.json toCSV prints the same escaped output as the escaping example. Reshape the data before toCSV to pick, rename, or flatten columns:
fx customers.json '@{id: x.id, name: x.name, city: x.address.city, tags: x.tags}' toCSVOutput:
id,name,city,tags
1,Alice,Berlin,vip;newsletter
2,Bob,Lyon,
3,Carol,Austin,beta