gpt4 book ai didi

ruby-on-rails - JSON - 嵌套子 RABL 或 JBuilder for Rails

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:13 26 4
gpt4 key购买 nike

我的对象看起来像:

[<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 持开放态度。我完全迷路了。

最佳答案

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

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

关于ruby-on-rails - JSON - 嵌套子 RABL 或 JBuilder for Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com