Created
April 15, 2014 22:32
-
-
Save jeshuamaxey/10784136 to your computer and use it in GitHub Desktop.
Small script to convert json data to csv
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
/* | |
* Small script to convert json data to csv | |
*/ | |
var fs = require('fs'); | |
var os = require('os'); | |
//name of files | |
var dataFile = 'data.json'; | |
var outputFile = 'output.csv'; | |
//array of keys from json object to head up the csv file (this could probably be done with code...) | |
var keys = ["city", "addr", "title", "lon", "phone", "web", "lat", "type", "id", "icon"]; | |
//add heading to the csv file | |
var csv = keys.join(',') + os.EOL; | |
//read in data | |
fs.readFile(dataFile, 'utf8', function(err, file) { | |
//check for file read error | |
if(err) console.log("Something went wrong :( \n" + err); | |
//parse json data | |
var data = JSON.parse(file); | |
//add each record as a row | |
data.forEach(function(record) { | |
//add each value as a entry in a row | |
keys.forEach(function(key, i) { | |
//only attempt to add entry if it exists | |
if(record[key]) csv += record[key] | |
//add the comma regardless of whether entry exists | |
//unless it is the last entry of this record | |
if(i!=keys.length) csv += ','; | |
}); | |
//new line at the end of each record | |
csv += os.EOL; | |
}); | |
//output the csv file when we're down | |
fs.writeFile(outputFile, csv); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment