Created
October 20, 2015 20:36
-
-
Save mmwtsn/8e2e02399a42fa94f363 to your computer and use it in GitHub Desktop.
Convert CSV line by line into JSON using streams in ES6.
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
import fs from 'fs' | |
import readline from 'readline' | |
let headers = [] | |
let lines = 0 | |
const rl = readline.createInterface({ | |
input: fs.createReadStream('input.csv'), | |
output: fs.createWriteStream('output.json') | |
}) | |
rl.on('line', (l) => { | |
let line = l.split(',') | |
let template = `{"${headers[0]}":"${line[0]}","${headers[1]}":"${line[1]}","${headers[2]}":"${line[2]}"}` | |
let json = '' | |
if (lines === 0) { | |
headers = line | |
} else if (lines === 1) { | |
json += '[\n ' | |
json += template | |
} else { | |
json += ',\n ' | |
json += template | |
} | |
rl.output.write(json) | |
lines++ | |
}) | |
rl.on('close', (l) => { | |
rl.output.write('\n]') | |
}) |
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
id | city | country | |
---|---|---|---|
1 | Berlin | Germany | |
2 | Amsterdam | Netherlands | |
3 | New York City | United States of America |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment