本文介绍了JSON-嵌套子级RABL或JBuilder for 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确定其树结构的地方.

Where ltree_val determines their tree structure.

我需要生成类似...

I need to generate something like...

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

我有由ltree值确定的子代,它们本身就是同一对象的元素.

Where I have children which are determined by an ltree value, which are themselves elements of the same object.

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

If I sort these objects by their ltree value, how can I create nested entries?

我对RABL或JBuilder开放.我完全迷路了.

I'm open to either RABL or JBuilder. I'm totally lost.

推荐答案

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

The answer was to use a recursive function...

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

这篇关于JSON-嵌套子级RABL或JBuilder for Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:54