问题
I have objects that look like:
[<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">]
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" }]
Where I have children which are determined by an ltree value, which are themselves elements of the same object.
If I sort these objects by their ltree value, how can I create nested entries?
I'm open to either RABL or JBuilder. I'm totally lost.
回答1:
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
This builds something like
[
{ "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"
}
}
]
}
]
来源:https://stackoverflow.com/questions/19457169/json-nesting-children-rabl-or-jbuilder-for-rails