D3 GDP Project issue with accessing JSON elements

D3 GDP Project issue with accessing JSON elements
0.0 0


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){


The above outputs :

If I change the console.log to


It outs the array data to the console. Like this:

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])

Or even:

 d3.json("url").get(function(error, d){
  d.data.forEach((data) => {
    console.log(data[0], data[1])

Edit: Didn’t notice you actually had the .json method wrapping the code till the end, scratch the first thing I said.


d3.json does not have a .get method, remove it and it will work, it is just simply , (where in your case, url="data.json") :

  if (error) throw error;