8

I have a csv with the following data:

world,country,state

World,US,CA

World,US,NJ

World,INDIA,OR

World,INDIA,AP

World,INDIA,TN

I need to convert in to a tree hierarchy as shown below:

{

    "name": "World",
    "children": [
      { "name": "US",
          "children": [
           { "name": "CA" },
           { "name": "NJ" }
         ]
      },
      { "name": "INDIA",
          "children": [
          { "name": "OR" },
          { "name": "TN" },
          { "name": "AP" }
         ]
      }
 ]
};

Then this tree will be used for tree visualization. Can any one help on this?

user1842231
  • 213
  • 1
  • 3
  • 8

1 Answers1

7

d3.nest is your friend!

Look at the Nest documentation for D3: https://github.com/d3/d3-collection/blob/master/README.md#nests

And here are some example I wrote when I was learning to use nest: https://gist.github.com/3176159

This question also helps: D3: use nest function to turn flat data with parent key into a hierarchy

user2357169
  • 109
  • 2
  • 9
PhoebeB
  • 8,434
  • 8
  • 57
  • 76
  • 2
    Thank you very much. It helped a lot. One more query though : can we change the tags of the hierarchy formed from d3.nset() In your examples you have "key" and "values" as tags where as I wanted to have my tags as "name" and "children". Any idea how to do this?? – user1842231 Nov 22 '12 at 11:00