TMoore TMoore - 10 months ago 66
JSON Question

d3.js graphing sub arrays from JSON

So I am attempting to draw a simple line graph. The path to the arrays are fairly long, It seems the forEach function is not looping through the array? Am I missing a function to successfully create which comes out as 'null' and d.air which comes out as 'NaN'?

data[0].STATION[0].OBSERVATIONS.date_time, and data[0].STATION[0].OBSERVATIONS.air_temp_set_1 are the arrays I want to plot

Here it is on blockbuilder:

Many thanks!

Answer Source

There are two things going on here.


data.forEach(function(d) { = format(data[0].STATION[0].OBSERVATIONS.date_time);
    d.air = +data[0].STATION[0].OBSERVATIONS.air_temp_set_1;

These don't work because both data[0].STATION[0].OBSERVATIONS.date_time, and data[0].STATION[0].OBSERVATIONS.air_temp_set_1 are arrays.

What you probably want is this.

var obs = data[0].STATION[0].OBSERVATIONS;
var dates =;
var air ={ return +d; }); = dates;
data.air = air;

What this leaves you with is an array of dates and and array of air temps.

Unfortunately, this leads to issue #2.


var line = d3.line()
    .x(function(d) { return x(; })
    .y(function(d) { return y(d.air); });

This function assumes that each object, d, takes the form {date: SINGLE_DATE_VALUE, air: SINGLE_NUMERIC_VALUE, etc} but what you actually have is data = {date:[ARRAY_OF_DATES, air: ARRAY_OF_TEMPERATURES, etc...}

To use the line function above, then you need to create an array of objects of the form {date: DATE_VALUE, air: AIR_TEMPERATURE_VALUE}. There are various ways you can do that depending on how you want your final data structured. Here's one way:

data.airTempByDate =, i){
    return {
        date: d,
        air: air[i]

Hope this makes sense! Here's a working block on blockbuilder with the fixes above.