Converting CSV to JSON in the Terminal
fx reads any text file line by line with -rs, so a few lines of JavaScript turn a CSV file into a JSON array of objects, with no extra CSV tool needed. Install fx first.
The examples use users.csv:
id,name,email,age,city
1,Alice,alice@example.com,31,Berlin
2,Bob,bob@example.com,27,
3,Carol,carol@example.com,,Lisbon
4,Dave,dave@example.com,45,BerlinRead a CSV File as an Array of Lines
-r treats input as raw text and -s collects every line into one array:
cat users.csv | fx -rs[
"id,name,email,age,city",
"1,Alice,alice@example.com,31,Berlin",
"2,Bob,bob@example.com,27,",
"3,Carol,carol@example.com,,Lisbon",
"4,Dave,dave@example.com,45,Berlin"
]Windows line endings (\r\n) are stripped too, so CRLF files need no extra step.
Convert CSV to JSON Objects Using the Header Row
Split each line on commas, take the first row as keys, and zip each remaining row with the header:
cat users.csv | fx -rs 'x => {
const [header, ...rows] = x.map(line => line.split(","));
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, r[i]])));
}'[
{
"id": "1",
"name": "Alice",
"email": "alice@example.com",
"age": "31",
"city": "Berlin"
},
...
]Convert Numeric Strings to Numbers and Empty Cells to null
CSV has no types, so every value above is a string. Add a cast step that turns empty cells into null and anything numeric into a number:
cat users.csv | fx -rs 'x => {
const [header, ...rows] = x.map(line => line.split(","));
const cast = v => v === "" ? null : isNaN(v) ? v : Number(v);
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, cast(r[i])])));
}'[
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"age": 31,
"city": "Berlin"
},
{
"id": 3,
"name": "Carol",
"email": "carol@example.com",
"age": null,
"city": "Lisbon"
},
...
]WARNING
cast also converts zip codes and IDs such as "007" to 7. Cast specific columns instead if leading zeros matter.
Convert TSV or Semicolon-Separated Files to JSON
Change the separator in split. For a tab-separated products.tsv, use "\t":
cat products.tsv | fx -rs 'x => {
const [header, ...rows] = x.map(line => line.split("\t"));
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, r[i]])));
}'European spreadsheets often export with ; and use a decimal comma. Split on ;, then fix the number columns in a second argument:
cat orders.csv | fx -rs 'x => {
const [header, ...rows] = x.map(line => line.split(";"));
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, r[i]])));
}' 'map(o => ({...o, order_id: Number(o.order_id), total: Number(o.total.replace(",", "."))}))'Input:
order_id;customer;total;status
1001;Alice;59,90;paid
1002;Bob;120,00;pending
1003;Carol;15,50;paidOutput:
[
{ "order_id": 1001, "customer": "Alice", "total": 59.9, "status": "paid" },
{ "order_id": 1002, "customer": "Bob", "total": 120, "status": "pending" },
{ "order_id": 1003, "customer": "Carol", "total": 15.5, "status": "paid" }
]Handle Quoted Fields With Commas
split(",") breaks on fields like "Acme, Inc.". This regex keeps quoted fields together and turns "" back into ":
cat contacts.csv | fx -rs 'x => {
const parse = line => [...line.matchAll(/(?:^|,)("(?:[^"]|"")*"|[^,]*)/g)]
.map(m => m[1].replace(/^"|"$/g, "").replace(/""/g, "\""));
const [header, ...rows] = x.map(parse);
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, r[i]])));
}'Input:
name,company,note
Alice,"Acme, Inc.",VIP
Bob,Globex,"said ""call me later"""
Carol,"Initech, LLC",Output:
[
{
"name": "Alice",
"company": "Acme, Inc.",
"note": "VIP"
},
{
"name": "Bob",
"company": "Globex",
"note": "said \"call me later\""
},
...
]This parser does not handle line breaks inside quoted fields, because -rs has already split the input on newlines. It also does not handle spaces between a comma and an opening quote. For CSV exported from spreadsheets with multi-line cells, use a full CSV parser.
Convert CSV to Newline-Delimited JSON (NDJSON)
To get one compact object per line instead of an array, stringify each row and join with newlines. fx prints string results without quotes:
cat users.csv | fx -rs 'x => {
const [header, ...rows] = x.map(line => line.split(","));
return rows.map(r => JSON.stringify(Object.fromEntries(header.map((h, i) => [h, r[i]])))).join("\n");
}' > users.ndjson{"id":"1","name":"Alice","email":"alice@example.com","age":"31","city":"Berlin"}
{"id":"2","name":"Bob","email":"bob@example.com","age":"27","city":""}
{"id":"3","name":"Carol","email":"carol@example.com","age":"","city":"Lisbon"}
{"id":"4","name":"Dave","email":"dave@example.com","age":"45","city":"Berlin"}fx reads that file back as a stream, one object at a time (see streaming mode). To save the regular JSON array instead, redirect the output of the previous commands to users.json.
Save a Reusable csv Function in .fxrc.js
Put the conversion in .fxrc.js so you don't have to retype it:
function csv(lines, sep = ",") {
const cast = v => v === "" ? null : isNaN(v) ? v : Number(v)
const [header, ...rows] = lines.map(line => line.split(sep))
return rows.map(r => Object.fromEntries(header.map((h, i) => [h, cast(r[i])])))
}cat users.csv | fx -rs csv
cat products.tsv | fx -rs 'x => csv(x, "\t")'Filter and Sort CSV Data in the Same Pipeline
Once the rows are objects, every fx argument after the conversion works on JSON. Keep users over 30, sort by age descending, and pick two fields:
cat users.csv | fx -rs csv '?.age > 30' 'sortBy(u => -u.age)' 'map(u => ({name: u.name, age: u.age}))'[
{ "name": "Dave", "age": 45 },
{ "name": "Alice", "age": 31 }
]To browse the converted data in the interactive viewer, pipe it into a second fx with no arguments: cat users.csv | fx -rs csv | fx.