Skip to content

Instantly share code, notes, and snippets.

@SpaceActuary
Last active June 17, 2016 20:45
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 SpaceActuary/05a817243f852a288608fab788fd85ee to your computer and use it in GitHub Desktop.
Save SpaceActuary/05a817243f852a288608fab788fd85ee to your computer and use it in GitHub Desktop.
CSV to JSON
name group year amount1 amount2
A ABC 1 168 10
A ABC 2 169.68 10
A ABC 3 176.4672 9
A ABC 4 171.173184 9
A ABC 5 184.86703872 8
B ABC 1 137 17
B ABC 2 132.89 18
B ABC 3 126.2455 18
B ABC 4 122.458135 18
B ABC 5 127.3564604 18
X XYZ 1 148 20
X XYZ 2 158.36 20
X XYZ 3 169.4452 19
X XYZ 4 177.91746 17
X XYZ 5 183.2549838 17
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:100%; height: 100% }
text { fill: #000; }
</style>
</head>
<body>
<h3></h3>
<p id="csv"></p>
<h3></h3>
<p id="json"></p>
<script>
console.clear()
function csv2json(csv){
var nested = d3.nest()
.key(function(d){ return d.name; })
.entries(csv)
var json = nested.map(function(d){
var namerecord = {};
// this is the variable that we grouped by
namerecord.name = d.key;
// this is another variable that I happen to know is constant for all
// years within a given "name", so I'll just grab the first value
namerecord.group = d.values[0].group;
// these are the time-series variables
// use a "map" to grab the year and amount from each of the child "values"
namerecord.amount1 = d.values.map(function(c){ return [c.year, c.amount1]; });
namerecord.amount2 = d.values.map(function(c){ return [c.year, c.amount2]; });
return namerecord;
});
return json;
}
d3.xhr("data.csv", function(csv){
console.log(csv)
d3.select("p#csv").html(csv.responseText);
})
d3.csv("data.csv", function(csv){
csv.forEach(function(d){
d.year = +d.year;
d.amount1 = +d.amount1;
d.amount2 = +d.amount2;
});
console.table(csv);
var json = csv2json(csv);
console.log(json);
d3.select("p#json").html(JSON.stringify(json, null, 2));
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment