Skip to content

Instantly share code, notes, and snippets.

@steve-taylor
Created September 19, 2025 05:44
Show Gist options
  • Select an option

  • Save steve-taylor/2f436633a3f438a44246c6135967b587 to your computer and use it in GitHub Desktop.

Select an option

Save steve-taylor/2f436633a3f438a44246c6135967b587 to your computer and use it in GitHub Desktop.

Convert JSON lines to CSV

This is a Node.js CLI utility to convert a file containing one JSON object per line into a CSV file.

The CSV file is written to stdout so that the output can be redirected or piped anywhere you want.

Example

node json2csv.js records.txt > records.csv

where each line in records.txt is a JSON object.

Caveats

The JSON object in the first line is used to define the structure of the CSV. The header row will be generated from its keys. Additional fields in subsequent records will be ignored.

const fs = require('node:fs')
const readline = require('node:readline')
const filename = process.argv[2]
if (!filename) {
throw new Error('Please specify a file name')
}
const fileStream = fs.createReadStream(filename)
const rl = readline.createInterface({input: fileStream, crlfDelay: Infinity})
let keys
rl.on('line', line => {
const record = JSON.parse(line);
if (!keys) {
keys = Object.keys(record)
console.log(getHeaderRow())
}
console.log(getDataRow(record))
})
function getHeaderRow() {
return keys.map(key => `"${asCsvValue(key)}"`).join(',')
}
function getDataRow(record) {
return keys
.map(key => `"${asCsvValue(record[key]) ?? ''}"`)
.join(',')
}
function asCsvValue(s) {
return s?.toString().replaceAll('"', '""')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment