D3 GDP Project issue with accessing JSON elements

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

      

The above outputs :

If I change the console.log to

console.log(d.data);

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.

1 Like

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") :

d3.json(url,function(error,d){
  if (error) throw error;
  console.log(d)
  })
1 Like

Hi Dereje1, I am starting the D3 challenges, and I´m having troubles fetching the JSON, EVERYBODY use the code you share:

d3.json(url,function(error,d){
if (error) throw error;
console.log(d)
})

However this didn´t work for me. The log never executed.
Instead this works perfect:

d3.json(url). then(function(error,d){
if (error) throw error;
console.log(d)
});

At first I was thinking was a typo error, then I copy and paste the code from serveral code pens and no one works… I simply I don´t get it.

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.