syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Node.js how to convert CSV to JSON?

While working on a Node.js app I encountered a use-case asking me to convert a CSV file from Yahoo Finance into a JSON file.

First, I wrote a simple bash script to GET the CSV file:
#!/bin/bash

# ~/aspy/bin/curl_gspc.bash

# This script should curl gspc prices into a two-column CSV file:
# ~/aspy/csv/gspc.csv
cd ~/aspy/
mkdir -p ~/aspy/csv/
gspcURL='http://ichart.finance.yahoo.com/table.csv?s=%5EGSPC'
curl $gspcURL | awk -F, '{print $1","$5}' > csv/gspc.csv
exit
Then, I installed some Node.js packages:
npm install -g csvtojson
npm install -g jsonfile
Next, I wrote a simple Node.js script:
/* ~/aspy/bin/gspcCSV2json.js

ref:
https://www.npmjs.com/package/csvtojson
https://www.npmjs.com/package/jsonfile

Demo:
cd ~/aspy/
node bin/gspcCSV2json.js
*/

//Converter Class 
var fs         = require("fs");
var Converter  = require("csvtojson").Converter;
var fileStream = fs.createReadStream("csv/gspc.csv");

//new converter instance 
var converter = new Converter({constructResult:true});

//end_parsed will be emitted once parsing finished 
converter.on("end_parsed", function (jsonObj) {
  var jsonfile = require('jsonfile');
  var file     = 'json/gspc.json';
  jsonfile.writeFile(file, jsonObj, function (err) { console.error(err); });});

//read from file 
fileStream.pipe(converter);
Then, I ran the Node.js script and it worked well:
cd   ~/aspy/
node bin/gspcCSV2json.js



syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me