1
def self.directory_hash(path, name=nil)
    data = {:parent => (name || path)}
    data[:children] = children = []
    Dir.foreach(path) do |entry|
      next if (entry == '..' || entry == '.')
      full_path = File.join(path, entry)
      if File.directory?(full_path)
        children << directory_hash(full_path, entry)
      else
      children << entry
      end
    end
    return data
  end

我使用了返回下面给出的 json 的上述方法:-

{:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}

现在在我看来,我想从上面的输出中显示结构,所以视图应该看起来像

public
 422.html
 applications
  1
   1
    1
    2
  2
.....
.....
.....

一个这样的

我有一个变量来保存这个 json

@structure = ApplicationVersion.directory_hash("public")

那么我需要编写什么代码来读取上面的 json 以便可以构建树?

4

1 回答 1

1

尝试:

your_hash = {:parent=>"public", :children=>["422.html", {:parent=>"applications", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>[{:parent=>"1", :children=>["configurations.xml"]}, {:parent=>"2", :children=>["configurations.xml"]}, "Projects.rar"]}, {:parent=>"2", :children=>[{:parent=>"9", :children=>["configurations.xml"]}, "rest.rar", {:parent=>"5", :children=>["configurations.xml"]}, {:parent=>"6", :children=>["configurations.xml"]}, {:parent=>"3", :children=>["configurations.xml"]}, {:parent=>"4", :children=>["configurations.xml"]}]}]}, {:parent=>"2", :children=>[{:parent=>"3", :children=>["Projects.rar"]}, {:parent=>"4", :children=>["rest.rar"]}]}]}, "500.html", "robots.txt", "favicon.ico", {:parent=>"data", :children=>[]}, "_index.html", "404.html"]}  

new_hash= your_hash.to_s.gsub(/(\[\"\S*\"\])/,'').gsub(/(\[|\]|\{|\})/,'').gsub('=>',',').gsub(',,',',')

new_hash.split(',').each {|i| puts i if i.strip[0] != ":"}
于 2013-03-01T12:39:12.420 回答