1

I have a csv data file which looks like this

root,y,i,5
root,c,b,a,7
root,c,b,z,2

I'd like to generate something similar to the flare.json data file like this:

{
  "name": "root",
  "children": [
    {
      "name": "y",
      "children": [
        {
          "name": "i",
          "value": 5
        }
      ]
    },
    {
      name: "c",
      "children": [
        {
          "name": "b",
          "children": [
            {
              "name": "a",
              "value": 7
            },
            {
              "name": "z",
              "value": 2
            }
          ]
        }
      ]
    }
  ]
}

I've seen others address a [similar question](Create hierarchy from csv in d3.js, but the data is even in the sense that every csv row has exactly n elements. I have varied lengths of n.

Can anyone help?

Community
  • 1
  • 1
Omar Wagih
  • 8,504
  • 7
  • 59
  • 75
  • It sounds like you would want to change whatever generates that data to generate a hierarchical structure. CSV isn't really meant for ragged formats like this and you will run into difficulties just processing it. – Lars Kotthoff Sep 27 '13 at 08:10

1 Answers1

5

I would use the d3 nest function to accomplish this. You can find documentation on how to use it here: http://bl.ocks.org/phoebebright/raw/3176159/

The solution would look something like this:

var nested_data = d3.nest()
  .key(function(d) { return d[0]; })
  .key(function(d) { return d[1]; })
  .entries(csv_data);
Solomon
  • 6,145
  • 3
  • 25
  • 34
  • This will only work if you have a defined number of columns. No? My problem is that my columns are variable. – Omar Wagih Sep 27 '13 at 14:52
  • if you only want to group by the first two columns, this should be fine. If you need to go with arbitrary columns, you could combine this with underscore.js, and traverse through the new nested data, nesting again when appropriate. – Solomon Sep 27 '13 at 15:14