数组os数组转换为d3.js json格式

时间:2013-07-30 14:48:03

标签: ruby json

我有这个数组数组:

[["abc", "123"], ["cde", "456"], ["cde", "674"]]

我希望以这种方式排列这个数组:

{ "name": "test", "children": [ {"name": "abc", "children": [ {"name": "123"} ]}, {"name": "cde", "children": [ { "name": "456"},{"name": "674"} ]}]}

如何用ruby语言进行转换?

提前致谢。

1 个答案:

答案 0 :(得分:2)

试试这个

 require 'json'
 src_arr= [["abc", "123"], ["cde", "456"], ["cde", "674"]]
 tmp = {} # to collect all common node first
 src_arr.each do |arr|
     if node = tmp[arr.first] # check if node exists
       node['children'] << {'name' => arr.last} # append of exists
     else
       # add node if does not exists
       tmp[arr.first] = {'name' => arr.first,'children' => [{'name' => arr.last}]}
     end
   end
 tree = {'name' => 'test','children' => tmp.values}
 puts tree

#=> {"name"=>"test", "children"=>[{"name"=>"abc", "children"=>[{"name"=>"123"}]}, {"name"=>"cde", "children"=>[{"name"=>"456"}, {"name"=>"674"}]}]}

puts JSON.generate(tree)

#=> {"name":"test","children":[{"name":"abc","children":[{"name":"123"}]},{"name":"cde","children":[{"name":"456"},{"name":"674"}]}]}