D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
SpaceActuary
Full window
Github gist
CSV to JSON
Built with
blockbuilder.org
<!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>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js