Skip to content

Instantly share code, notes, and snippets.

@aendra-rininsland
Last active August 29, 2015 14:08
Show Gist options
  • Save aendra-rininsland/59fbe125f16c060ec14a to your computer and use it in GitHub Desktop.
Save aendra-rininsland/59fbe125f16c060ec14a to your computer and use it in GitHub Desktop.
Convert Google Sankey chart data to D3.js Sankey data (nodeJS)
/**
* Convert Google Sankey chart data to D3.js Sankey data (nodeJS)
* Usage: node convert_google_to_d3.js in-file.json out-file.json
*
* Requires: lodash — npm install lodash
*/
'use strict';
var _ = require('lodash');
var fs = require('fs');
if (process.argv.length < 4) {
console.log('Usage: node convert_google_to_d3.js in-file.json out-file.json');
process.exit(1);
} else {
var inFile = process.argv[2];
var outFile = process.argv[3];
}
fs.readFile(inFile, function(err, data){
var nodes = [],
links = [];
var inData = JSON.parse(data);
inData.forEach(function(v) {
var index1 = _.findIndex(nodes, {'name': v[0]});
var index2 = _.findIndex(nodes, {'name': v[1]});
if (index1 === -1) { // new node
index1 = nodes.push({'name': v[0]}) - 1;
}
if (index2 === -1) { // new node
index2 = nodes.push({'name': v[1]}) - 1;
}
links.push({'source': index1, 'target': index2, 'value': v[2]});
});
fs.writeFile(outFile, JSON.stringify({'nodes': nodes, 'links': links}), function(err){
if (err) {
console.log('Error writing file.');
process.exit(1);
} else {
console.log('D3 Sankey data successfully written to: ' + outFile);
process.exit(0);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment