【发布时间】:2015-10-18 01:38:00
【问题描述】:
我有一个类似于以下内容的树状对象图:
{
:name => "Grandparent",
:children => {
:child_a => {
:name => "Parent A",
:children => {
:grandchild_a_a => {
:name => "Child A-A",
:children => {}
}
:grandchild_a_b => {
:name => "Child A-B"
:children => {}
}
}
}
:child_b => {
:name => "Parent B",
:children => {}
}
}
}
我想生成反映这种结构的 JSON。不知道子嵌套有多深,每一层的属性都是一样的。子哈希中的键很重要,必须保留。
我想使用 JBuilder 部分来表示一个级别,然后递归调用它。到目前为止,这是我的模板:
# _level_partial.json.jbuilder
# passing the above object graph as :level
json.name level[:name]
json.children do
level[:children].each do |key, child|
# How do I map the following to the given key?
json.partial! "level_partial", :level => child
end
end
我可以很容易地通过部分调用为每个孩子生成 JSON,但这会将其直接插入 JSON 输出。如何将部分结果映射到特定的哈希/对象键?
【问题讨论】:
标签: ruby-on-rails json jbuilder