Skip to content

Instantly share code, notes, and snippets.

@blahah
Last active October 12, 2020 13:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blahah/61f6ce8da6d75ef1fd0899356d8da127 to your computer and use it in GitHub Desktop.
Save blahah/61f6ce8da6d75ef1fd0899356d8da127 to your computer and use it in GitHub Desktop.
{ "one": "hello", "two": "venus", "three": "help", "four": "I'm stuck here" }
{ "one": "hello", "two": "mercury", "three": "help", "four": "I'm stuck here" }
{ "one": "hello", "two": "earth", "three": "help", "four": "I'm stuck here" }
{ "one": "hello", "two": "mars", "three": "help", "four": "I'm stuck here" }
// usage: node json-to-csv.js < input > output.csv
// example: node json-to-csv.js < eg.jsonstream
var pump = require('pump')
var split = require('split')
var through = require('through2')
var keys = ['one', 'two', 'four']
console.log(keys.join(','))
pump(
process.stdin,
split(JSON.parse, null, { trailing: false }),
through.obj(csvify),
process.stdout,
done
)
var n = 0
function arrayToCSV (d) { return d.map(v => `"${v}"`).join(',') + "\n" }
function csvify (data, enc, next) {
var csvline = arrayToCSV(keys.map(k => data[k]))
this.push(csvline)
n += 1
next()
}
function done (err) {
if (err) throw err
console.error(`converted ${n} JSON objects to CSV`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment