JSON – 为Rails嵌套子RABL或JBuilder

我的对象看起来像:

[, , , , ] 

ltree_val确定其树结构的位置。

我需要生成像……

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

我有孩子的地方由ltree值决定,它们本身就是同一个对象的元素。

如果我按照ltree值对这些对象进行排序,我该如何创建嵌套条目?

我对RABL或JBuilder持开放态度。 我完全迷失了。

答案是使用递归函数……

 # 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" } } ] } ]