Skip to content

Instantly share code, notes, and snippets.

@mmwtsn
Created October 20, 2015 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmwtsn/8e2e02399a42fa94f363 to your computer and use it in GitHub Desktop.
Save mmwtsn/8e2e02399a42fa94f363 to your computer and use it in GitHub Desktop.
Convert CSV line by line into JSON using streams in ES6.
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]')
})
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