2013-10-18 34 views
3

我有一个看起来像对象:JSON - 嵌套Rabl的儿童或者JBuilder的Rails的

[<ltree_val: "1", contents: "blah">, 
<ltree_val: "1.1", contents: "blah">, 
<ltree_val: "1.1.1", contents: "blah">, 
<ltree_val: "2", contents: "blah">, 
<ltree_val: "2.1", contents: "blah">] 

凡ltree_val决定了他们的树结构。

我需要生成类似...

[{ "data" : "1", 
    "children" : 
     [{ "data" : "1.1", 
     "children" : 
       [{ "data" : "1.1.1" }] 
     }] 
    }, 
    { "data" : "2" }] 

在那里我有它们通过ltree值确定孩子,这本身就是同一对象的元素。

如果我按照它们的ltree值排序这些对象,我如何创建嵌套条目?

我对RABL或JBuilder都是开放的。我完全迷失了。

回答

3

答案是使用递归函数...

# encoding: UTF-8 

def json_ltree_builder(json, ltree_item) 
    json.title t(ltree_item.title) 
    json.attr do 
    json.id ltree_item.id 
    end 
    json.metadata do 
     json.val1 ltree_item.val1 
     json.val2 ltree_item.val2 
    end 
    children = ltree_item.children 
    unless children.empty? 
    json.children do 
     json.array! children do |child| 
     json_ltree_builder(json, child) 
     end 
    end 
    end 
end 

json.array! @menu_items do |menu_item| 
    json_ltree_builder(json, menu_item) 
end 

这建立类似

[ 
    { "title":"Title 1", 
    "attr" : { 
     "id": 111 
    }, 
    "data" : { 
     "val1" : "Value 1", 
     "val2" : "Value 2" 
    }, 
    "children" : [ 
     { 
     "title":"Child 1", 
     "attr" : { 
      "id": 112 
     }, 
     "data" : { 
      "val1" : "Value 1", 
      "val2" : "Value 2" 
     } 
     }, 
     { 
     "title":"Child 2", 
     "attr" : { 
      "id": 112 
     }, 
     "data" : { 
      "val1" : "Value 1", 
      "val2" : "Value 2" 
     } 
     } 
    ] 
    } 
] 
+1

哪个文件应该递归函数驻留在?它是控制器,是部分还是帮手? – MSC

+0

json参数对我不起作用。它报告错误的参数数量(1为2)。你有这个工作吗? – Khanetor