【问题标题】:Convert a single level JSON adjacency list to nested JSON tree将单级 JSON 邻接列表转换为嵌套 JSON 树
【发布时间】:2014-04-15 20:45:08
【问题描述】:

我有一个单级邻接列表,我从关系数据库构建到 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 的嵌套级别上回溯的问题。算法教科书中的示例不足以与我的经验相匹配,我的经验是通过将一些基本数据(如数字或字符串)推送到堆栈来简单地处理回溯问题。

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

【问题讨论】:

  • 为什么不使用像 act_as_tree 或 ancestry 或 awesome_nested_set 这样的 AR 模型添加层次结构的 gem?
  • @MarkThomas 是的,虽然它会让我的生活更轻松,但我正在开发一个已经在这些线上开发的应用程序。

标签: ruby json algorithm tree adjacency-list


【解决方案1】:

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

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? 行,因为您的输入哈希不包含儿童 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 键与一个空数组作为值,而不是完全省略它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2021-11-25
    • 2020-03-21
    • 2021-03-07
    • 2016-10-05
    相关资源
    最近更新 更多