ruby - 将单级 JSON 邻接列表转换为嵌套的 JSON 树

标签 ruby json algorithm tree adjacency-list

在 Rails 4 项目中,我有一个单级邻接表,它是从关系数据库构建到 JSON 对象中的。看起来像

{
    "6": {
        "children": [
            8,
            10,
            11
        ]
    },
    "8": {
        "children": [
            9,
            23,
            24
        ]
    },
    "9": {
        "children": [
            7
        ]
    },
    "10": {
        "children": [
            12,
            14
        ]
    ...
}

现在我想把它变成一个 JSON 结构,供 jsTree 使用,看起来像

{
   id: "6",
   children: [
            { id: "8", children: [ { id: "9", children: [{id: "7"}] }]
            { id: "10", children: [ { id: "12",...} {id: "14",...} ] }
 ...and so on
}

我在构建这种树时面临的问题是在 JSON 的嵌套级别上进行回溯。算法教科书中的示例不足以与我的经验相匹配,我的经验是通过将一些基本数据(如数字或字符串)插入堆栈来简单地处理回溯问题。

感谢任何有关构建此类树的实用方法的帮助。

最佳答案

假设有一个根元素(因为它是一棵树),您可以使用非常短的递归方法来构建树:

def process(id, src)
  hash = src[id]
  return { id: id } if hash.nil? 
  children = hash['children']
  { id: id, children: children.map { |child_id| process(child_id.to_s, src) } }
end

# the 'list' argument is the hash you posted, '6' is the key of the root node
json = process('6', list)

# json value:
#
# {:id=>"6", :children=>[
#   {:id=>"8", :children=>[
#     {:id=>"9", :children=>[
#       {:id=>"7"}]}, 
#     {:id=>"23"}, 
#     {:id=>"24"}]}, 
#   {:id=>"10", :children=>[
#     {:id=>"12"}, 
#     {:id=>"14"}]}, 
#   {:id=>"11"}]}

我添加了 return { id: id } if hash.nil? 行,因为您的输入哈希不包含 child 7、11、12、14、23、24 的条目。如果他们的条目就像下面一样,您可以删除该行。

"7" => { "children" => [] },
"11" => { "children" => [] },
"12" => { "children" => [] },
"14" => { "children" => [] },
"23" => { "children" => [] },
"24" => { "children" => [] }

在那种情况下,该方法将产生 {:id=>"7", :children=>[]} 而不是 {:id=>"7"} 如果你愿意,你可以通过包含一个 children.empty? 检查来改变它,在这种情况下返回一个只有 :id 键的散列(就像我在hash.nil? 检查)。但是,就一致性而言,我可能更喜欢将 children 键作为值与一个空数组一起出现,而不是完全省略它。

关于ruby - 将单级 JSON 邻接列表转换为嵌套的 JSON 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082599/

相关文章:

ruby - 获取点周围的坐标

ruby - 查找未分配的弹性 IP

HTMLEntities 解码为 ascii 194,不应该是 160 吗?

json - JAX-RS + JPA,如何只更新/合并实体字段的一个子集?

javascript - 将缺失的键、值和数据添加到 json 对象

json - 如何使用 Express 或 Body-Parser 拒绝无效的 JSON 正文

c++ - 使用 Boost 从 C++ 中的样本 vector 计算平均值和标准差

c++ - 在 C/C++ 中快速显示波形

java - 来自枪的 Libgdx 爆炸

python - 如何将 Faktory 与 ruby​​ 作业和 python 作业一起使用?