I’m working on the D3 GDP bar graph project and I’ve had success building a graph that charts random bars using a for loop and the Math.random() function, but I’m having trouble tweaking it to display the GPD JSON data.
// Console.logs the JSON data in the browser console
d3.json("data.json").get(function(error, d){
console.log(d);
So now I’m able to see the Array[“1947-04-01”, 246.3] data. Those are the arrays I want to retrieve from the JSON file and plot to my bar graphs. I’m having trouble accessing these array elemets (date and billions of dollars in the economy). I’ve attempted to access this data in many ways, most recently like this:
for(var i = 0 ; i < d.length; i++){
myData.push(d.data["DATE", "VALUE"]);
I’ve also tried it with a 0 and a 1 in the array. Nothing I try works. What’s the proper way to retrieve this data from the JSON file in a D3 program?
Hey. I don’t know anything about D3 but you were accessing the data outside of the success state of the .json method that, being asynchronous, wouldn’t finish in time for your for loop and you were accessing the object wrongly (you should’ve looped the d.data, not the d).
Try it like this:
d3.json("url").get(function(error, d){
for (var i = 0; i < d.data.length; i++) {
console.log(d.data[i][0], d.data[i][1])
}
});
Haven’t used d3 in a minute, maybe you are on a newer version that ‘promisifies’ ajax requests (rather than using callbacks) ? I’m not sure, I’ll look into it.