Last active
August 29, 2015 14:24
-
-
Save logalleon/458f6d86ad3b171e2557 to your computer and use it in GitHub Desktop.
JSON 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
/* | |
* Logan H. Sobczak 6/24/15 | |
* Converts arbitrary JSON to CSV | |
* | |
* node json-to-csv.js [file1.json, file2.json, ... ] | |
* outputs to ./csv/file1.csv, ./csv/file2.csv . . . | |
*/ | |
var fs = require('fs'), | |
files = process.argv.slice(2); | |
fs.exists(__dirname + "/csv", function (exists) { | |
// Make an output folder | |
if (!exists) fs.mkdirSync(__dirname + "/csv"); | |
// Iterate over files | |
files.forEach(function (file) { | |
// Check for json | |
if (file.toLowerCase().indexOf("json") == -1) { | |
console.err("Are you sure " + file + " is a json file?"); | |
return; | |
} | |
fs.readFile(__dirname + "/" + file, function (err, data) { | |
if (err) throw (err); | |
try { | |
var data = JSON.parse(data.toString()); | |
} catch (err) { | |
// Invalid JSON | |
throw (err); | |
} | |
var out = json_to_csv(data, 0); | |
fs.writeFileSync(__dirname + "/csv/" + file.split('.')[0] + ".csv", out); | |
}); | |
}); | |
}); | |
function json_to_csv (node, depth) { | |
// Array for Array.join rather than concatenating a (potentially) very large string | |
var out = []; | |
// Iterate over the properties of the node | |
for (var prop in node) { | |
// Format the depth in the rows | |
for (var i = depth; i; i--) { | |
out.push(","); | |
} | |
if (prop) { | |
// Wrap numbers in quotes to avoid truncation | |
if (Number(prop) || prop == 0) { | |
out.push("'"); | |
out.push(prop); | |
out.push("'"); | |
} else { | |
out.push(prop); | |
} | |
out.push(","); | |
} | |
if (typeof node[prop] == "object") { | |
// New row for new object | |
out.push("\n"); | |
// Recursion + increase depth | |
out.push(json_to_csv(node[prop], depth + 1)); | |
} else { | |
// Wrap numbers in quotes to avoid truncation | |
if (Number(node[prop])) { | |
out.push("'"); | |
out.push(String(node[prop])); | |
out.push("'"); | |
} else { | |
out.push(String(node[prop])); | |
} | |
} | |
out.push("\n"); | |
} | |
// Join text and return | |
return out.join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment