JSON - 在Rails中使用RABL或JBuilder嵌套子元素

3

我有一些看起来像这样的对象:

[<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">]
< p > ltree_val 确定它们的树形结构。 < /p > < p > 我需要生成类似于... < /p >
[{ "data" : "1",
  "children" : 
      [{ "data" : "1.1",
         "children" : 
              [{ "data" : "1.1.1" }]
       }]
  },
  { "data" : "2" }]

我有一些由ltree值确定的子元素,它们是同一个对象的一部分。

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

我可以使用RABL或JBuilder,但我完全不知道该怎么做。

1个回答

5
答案是使用递归函数...
# 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
JSON参数对我不起作用。它报告参数错误(1个参数需要2个)。你成功解决了这个问题吗? - Khanetor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接