2

I have nested arrays in my json data, but I don't know how to call them in the d3 (beginner).

In the example below, I am trying to build an SVG bar chart, using data from the "January" array, nested in the "meals" array in Json.

The Json looks like this:

{
"meals":[
    {"january":[
        {},{}
    ]},

    {"february":[
        {},{}
    ]},

    {"march":[
        {},{}
    ]},
  }

And the d3 code looks like this. "chart" takes the user input of a drop down menu. In this case, it basically returns "meals":

    var chart = selection.options[selection.selectedIndex].id;

    var dataset = data[chart];

    var svg = d3.select ("body") 
                .append ("svg")
                .attr("width", w)
                .attr("height", svgHeight+30);


    svg.selectAll("rect") 
                .data(dataset.january) //***HERE is where I'm having trouble***
                    .enter()
                    .append("rect") 
5
  • Is the json object already loaded? Or is it in a separate file? Commented Jul 9, 2013 at 19:56
  • Yes, it's in a separate file and already loaded. Commented Jul 9, 2013 at 20:03
  • .data(dataset) should work then; if not you probably should post a jsfiddle. Any number of things could be going wrong. Commented Jul 9, 2013 at 20:04
  • The value of data.meals is an array. Hence you would have to access it with dataset[0], dataset[1], .... However, since each of the objects only contains one property, you might wan to use an object instead of an array of objects. Commented Jul 9, 2013 at 20:12
  • hhmmm...that doesn't seem to work. The page loads, but no rect is created. I need arrays, because I am trying to create a double bar chart and will be adding additional data. Commented Jul 9, 2013 at 21:52

1 Answer 1

1

d3.nest() can convert data like that into parseable arrays. These 'tutorial' examples are great: http://bl.ocks.org/phoebebright/raw/3176159/

Given that it's feasible with your project, it might otherwise be better to simply change your data formatting for an easier traversal e.g.

{
"meals":[
    {"name":"salad","month":"january"},
    {"name":"burger","month":"february"}, //etc...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.