Last active
October 12, 2020 13:03
-
-
Save blahah/61f6ce8da6d75ef1fd0899356d8da127 to your computer and use it in GitHub Desktop.
json-to-csv example for https://www.reddit.com/r/node/comments/iapf5u/fastest_csvformatter_library/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ "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" } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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